WordPress is a standalone application and powerful CMS based on PHP and MySQL with unlimited capabilities. It is used to formulate websites and create complex blogs easily on your site. This is an extremely useful tool for small businesses to exploit. In wordpress, once your site is created you have the ability to edit, add, delete and anything else you need to the content, without any knowledge of HTML. We can extend its functionality by using plugins.

In this article, i will show you how to develop a simple ‘quote of the day’ plugin. Here I have used the plugin directory named as wp-quotd. For this, only you need to have a basic knowledge of php scripting. First of all before creating a new plugin we should understand about plugins.

What are WordPress Plugins ?

Word press plugin is a program or a set of one or more functions, written in PHP scripting language. It adds a specific set of features to wordpress site, and also improves other applications and usability of wordpress sites. The following picture( wp-pic(1)) describes the structure of wordpress plugin directory.

wp-pic(1) : WordPress Plugin Directory

wp-pic(1) : WordPress Plugin Directory

 

Why Write Plugins ?

Mainly these following are the reasons for writing plugins in wordpress,

  • Extend existing functionality.
  • Solve a problem.
  • Save time.
  • Probability ( Changing themes , Using on multiple sites ).

Plug-ins are a great way to improve the functionality of your blog by adding in extra features. These can be placed anywhere inside your template by function hooks.

 

How to write a WordPress Plugin ?

WordPress plugins can be defined in a single file or a directory of files. Plugins always put in a directory , it gives us more flexibility and allows to use common structures and folder layouts between projects and will add a level of maintainability. Assigning unique names, documenting and organizing the plugin files is very important part of plugin creation. Directory name should in ‘dashes’ and not ‘underscores’.

Before developing a plugin, we should know the following rules. They are,

  • Always assigning a unique name to your plugin so that it does not collide with names used in other plugins.
  • Make sure you comment wherever and whenever necessary in the code.
  • Test the Plugin in your localhost along with latest version of wordpress.

Mainly the following two functions are used for wordpress plugin creation. They are called “hooks”.

add_action ($tag, $func)
add_filter ($tag,$func)

The difference between these two functions are,

  • add_action –> does an action at various points of wordpress execution.
  • add_filter –> does filtering the data.

To create a directory to hold your plugin and give it a name matching your plugin. Then, within that directory, create your main PHP file, again naming the file with the name of your Plugin:

Generally, use the following folder structures are used:

  • wp-plugin-name/name of the plugin
  • wp-plugin-name.php – main plugin class
  • readme.txtoptional. It describes the plugin details.

For Example,

wp-quotd

– >wp-quotd.php

If your plugin is requires any images, javascript, css, or additional PHP files, you will put it in subdirectory within the plugin directory as well:

wp-quotd

->css

->img

->js

 

WP Folder Structure

The WordPress plugins are kept under \wp-content\plugins\ directory. So any new plugins created needs to be used inside this folder. Inside wp-content you will find a plugins directory (see the above mentioned picture wp-pic(1) for reference). In here, all of your individual plug-ins will be listed.

For smaller plug-ins which only require a single php file you have the option to place this directly into the plug-ins/ directory. However we can create subdirectories (inside your plugin directory) for developing in the case of complicated applications. Inside there you can include JavaScript, CSS, and HTML files along with your PHP functions.

A readme.txt file include the author name and what the plugin does. Optionally it also contains the details about each revision and which updates have come out.

 

Filters and Actions

Actions and filters are two completely different to actions. The concepts which relate in the ways how they manipulate plugin data. Actions are used to add something to the existing page such as stylesheets, JavaScript dependencies etc. Filters are used to manipulate data coming out of the database prior to going to the browser, or coming from the browser prior to going into the database.

 

Creating a Plugin

In this article I will show a step by step guide on how to create a wordpress plugin. The first step for making plugin is create database tables automatically rather than executing an SQL query directly. For this we use the dbDelta function which is located in wp-admin/includes/upgrade.php(It is not loaded by default .We will have to load this file ). There are some instructions for using dbDelta function. They are,

  • Must put each field on its own line in your SQL statement.
  • Should have two spaces between the words PRIMARY KEY and the definition of primary key.
  • Should include at least one KEY.
  • Should use the keyword KEY (rather than INDEX ).
  • Should not use any apostrophes or back ticks around field names.

Create a PHP function within your plugin that adds a table or tables to the WordPress MySQL database. And ensure that wordpress calls the function when the plugin is activated. In this article, I have write those code into the file named as wp-quotd-install.php and the function is called wpqotd_install().

Now going to initialized the plugin by using hooks and predefined WordPress functions. A hook is an event listener that is trigger based on outside events occurring. If the plugin needs to perform any type of setup, such as database table creation, you can write the code into the plugin install function.

 

For Example,

function wpqotd_install()
{
$wp_qotd_sql = “CREATE TABLE ‘wp_qotd’ (
qid int(11) NOT NULL auto_increment COMMENT ‘Quote ID’,
blog_id int(11) NOT NULL COMMENT ‘Current Blog ID’,
author varchar(128) NOT NULL COMMENT ‘Quote Author Name’,
cite varchar(255) NOT NULL COMMENT ‘Quote CITE Reference URL’,
quote text NOT NULL COMMENT ‘Quote’,
PRIMARY KEY (qid),
KEY ‘blog_id’ (blog_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT=’WP Quote Of The Day’;”;
dbDelta($wp_qotd_sql);
}
register_activation_hook(__FILE__,’wpqotd_install’);

Then, when a user activates your plugin, any function that has been registered with the activation hook will be executed.

If you want to add some custom JS files in your plugin need to operate, you can also do this by using the add_action hook. If your plugin focuses on one main class, put that class in the main plugin file, and add one or more separate files for other functionality.

When creating a new plugin you will need to start with a simple PHP file. This should be named by your plugin’s official name. For example, In this plugin created is “Quote of the Day” ( plugin name: wp-qotd). So file name is wp-quotd.php.

The first lines of your plug-in (it is called File Header) must be comment the information like plugin name, description, version, author etc. When we try to create a complex functionality plugin then we can splitting those into multiple files and folders might be easier to understand.

Below is an example code for sample File Header

<?php /*

Plugin Name : Plugin Name here (for example: wp-qotd )

Plugin URI : http://www.yourpluginurlhere.com/

Version : Current Version

Author : Name please

Description : What does your plugin do and what features doest offer.

*/

?>

 

To Create Administration Menu

To add an administration menu, you must do the following three things:

  1. Create a function that contains the menu-building code.

    For Example,

<? php

function wpqotd_createmenu()

{

              add_options_page(‘WP-QOTD’, ‘WP-QOTD’, 10, ‘wp-qotd-admin’, ‘wpqotd_management’);

}

?>

  1. Register the above function by using the admin_menu action hook.

add_action( ‘admin_menu’, ‘wpqotd_createmenu’ );

  1. Then create the HTML output for the page displayed when the menu item is clicked.

 

Create Widgets for our plugin

Now am going to create a widget for the plugin that I have created here as a sample. This widget will be a PHP class extending the core WordPress class Wp_Widget. File is named as wp_qotd_widget.php. The basic structure of the widget page is as follows,

<?php

// widget class

class WpQotdWidget extends WP_Widget

{

//constructor

function WpQotdWidget()

{

parent::WP_Widget(false, $name = ‘Quote of the day’);

}

// widget settings*/

function widget($args, $instance)

{

/** … **/

}

// widget form creation

function form($instance)

{

//Defaults

$title = esc_attr( $instance[‘title’] );

?>

<p><label for=”<?php echo $this->get_field_id(‘title’); ?>”><?php _e(‘Title:’); ?>

<input class=“widefat” id=”<?php echo $this->get_field_id(‘title’); ?>” name=”<?php echo $this->get_field_name(‘title’); ?>” type=“text” value=”<?php echo $title; ?>” /></label>

</p>

<?php }//end of function form

}//end of class

// To register WpQotd plugin Widget

add_action(‘widgets_init’, create_function(”, ‘return register_widget(“WpQotdWidget”);’));

?>

The widget can then be registered using the widgets_init hook. The WP_Widget class is located in wp-includes/widgets.php.

 

General plugin development guidelines :

WordPress does not enforce any strict rules on plugins. Plugins have a complete control over the WordPress web site. However the following things are keep it in you mind.

-> Security :

Exploits such as SQL injection or Cross-Site Request Forgery (CSRF) may pose serious security threat to the users of your plugin, if particular care is not taken.

WordPress provides some simple mechanisms to prevent these threats

  • $wpdb->prepare() : creating database queries
  • $wpdb->insert() : Inserting data into the database
  • $wpdb->update(): Updating data of database.
  • wp_nonce_url(): This function is mainly used for links, and wp_nonce_field() is a function used for forms in combination with check_admin_referer()/check_ajax_referer() that will protect your requests against CSRF.

-> Performance :

Plugins can sometimes create serious overhead issues and affect the performance of the entire site. Therefore, it is important to follow some guidelines. They are,

  • Should take care about of the number of MySQL queries. If you need to use several complicated queries, you can use built-in WordPress cache.
  • To enable caching, add this line to the WordPress wp-config.php file:

    define(‘WP_CACHE’, true);

  • Loading plugin localization data only when necessary is another performance improvement.
  • The same goes for JavaScript usage—load the scripts only on those pages where your plugin needs them.
  • Do not add a burden to the WordPress engine when they are not needed.
  • Optimization needed that means use only required resources to do the job.

 

How to use the sample plugin “ wp-qotd” ???

The following steps are required to use the above mentioned sample plugin ‘Quote of the Day’.

  1. Download the “wpqotd.zip” to your local hard drive.
  2. Then extract files.
  3. All files are located into the directory “wp-content/Plugins/wp-qotd”.
  4. Activate the plugin through the “plugins” menu in wordpress admin area.

OR

  1. Download the “wpqotd.zip” to your local hard drive.
  2. Then go to the wordpress admin area. Click the “Plugins” menu. Then click the “Add New” link.
  3. From that page, Click the “upload” link and upload the “wpqotd.zip” from your local hard drive. Then click to install.
  4. Then activate the plugin through the “plugins” menu in wordpress admin area.

wp-qotd1

wp-pic(2) : Screenshot after installing the Plugin

After completing the above mentioned 4 steps, the following steps are commonly required to display the quotes in home page, inner pages etc.

  1. Go to the links Appearance -> widgets. Here we can see the widget named as “Quote of the day”. Drag and drop those into the page where you want to display the quotes as an output.

wp-qotd2

  1. Result will be shown in the website page that you created before. If there is no quotes in the database then it shows the message “No quotes found in the database”
  2. Please add new quotes into the database by using the following steps.

    Go to settings -> WP-QOTD. Here you can found the button ( Add Quote) for inserting new quotes into the database.

wp-qotd3

  1. Please add more than one quotes into the database. You can view that quotes randomly displayed into website page as an output.

wp-qotd4

Conclusion :-

WordPress is powerful CMS with unlimited capabilities. We can extend the functionality of wordpress by using a plugin. WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language. WordPress Plugins allow easy modification, customization, and enhancement to a WordPress blog. Plugins interact with wordpress in the same way wordpress interacts with itself. The WordPress plugins are kept under \wp-content\plugins\ directory assigning with unique names to avoid the conflicts with other plugins.

The full source code of wp-qotd plugin can be downloaded from here