WordPress Plugin Development Tutorial from scratch

WordPress Plugin Development Tutorial from scratch

Wordpress Plugin Development

Following sections cover all necessary aspects when creating a wordpress plugins from scratch. for details you can visit wordpress official site for Plugins Resources

Names, Files, and Locations

 

Plugin Name

Plugin name should be unique .you have to search on wordpress plugins page or google to check if your plugin name is unique. Suppose you have to create a plugin related with slider so include name "slider" in your plugin.

Plugin Files

Now have to create a PHP file name with your plugin name, Suppose you are creating plugin related with horoscope display ,plugin file name could be abc-horoscope.php. wordpress-install-dir-plugins Alternatively you can split all files in different sub folder in main plugin folder. This help well organise all the plugins files for wide functionalty plugin.. See: http://codex.wordpress.org/Determining_Plugin_and_Content_Directories for more details. In the rest of this Tutorial , "the Plugin PHP file" refers to the main Plugin PHP file, whether in wp-content/plugins/ or a sub-directory.

Readme File

Create a readme.txt file in a standard format if you want to host http://wordpress.org/extend/plugins/,, and include it with your Plugin. See http://wordpress.org/extend/plugins/about/readme.txt for a description of the format. Note that the WordPress plugin repository takes the "Requires" and "Tested up to" versions from the readme.txt in the stable tag.

Home Page

This is like the home page of your plugin . This page should contains - how to install the Plugin - what it does, what versions of WordPress it is compatible with- - what has changed from version to version of your Plugin - and how to use the Plugin. etc

File Headers

Now it's time to put some information into your main Plugin PHP file.

Standard Plugin Information

The top of your Plugin's main PHP file must contain a standard Plugin information header. This header lets WordPress recognize that your Plugin exists, add it to the Plugin management screen so it can be activated, load it, and run its functions; without the header, your Plugin will never be activated and will never run. Here is the header format:

/*
Plugin Name: Name Of The Plugin
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: A brief description of the Plugin.
Version: The Plugin's Version Number, e.g.: 1.0
Author: Name Of The Plugin Author
Author URI: http://URI_Of_The_Plugin_Author
License: A "Slug" license name e.g. GPL2
*/

The minimum information WordPress needs to recognize your Plugin is the Plugin Name line. The rest of the information (if present) will be used to create the table of Plugins on the Plugin management screen. The order of the lines is not important. So that the upgrade mechanism can correctly read the version of your plugin it is recommended that you pick a format for the version number and stick to it between the different releases. For example, x.x or x.x.x or xx.xx.xxx The License slug should be a short common identifier for the license the plugin is under and is meant to be a simple way of being explicit about the license of the code. Important: file must be in UTF-8 encoding.

License

It is customary to follow the standard header with information about licensing for the Plugin. Most Plugins use the GPL2 license used by WordPress or a license compatible with the GPL2. To indicate a GPL2 license, include the following lines in your Plugin:

;

 

Developing your Plugins (Programming Parts)

After providing some information regarding the plugins now, it's time to make your Plugin actually do something. Following section describe some general ideas about Plugin development, and describes how to accomplish several tasks your Plugin will need to do.

WordPress Plugin Hooks

Most of the time in wordpress plugins development it requires to execute some hooks Hooks are PHP function that alter/modify default core functions,there are 2 types of hooks i) Action Hooks - Action hooks are those kind of hooks that execute in wordpress system events like when creating a new posts , posting a comment, admin menu load etc. Details visit Action Hooks ii) Filter Hooks - Filter hooks are for modifying/altering text (title,body,fields etc) on site ,it executes before displaying it to browser or saving it to database .Suppose you want to replace a text in your post "anna hajare" with new one "kejriwal" you have to use "the_content" hooks .Details Filter Hooks For details overview on all wordpress available hooks visit Plugin API.

Template Tags

To add more funcitonality sometime we also need custom Template Tags. Those who wants to use your Plugin can add these "tags" to their theme, in the sidebar, post content section, or wherever it is appropriate. For example if your plugins provide social media share links functionality, there should a template tag available something like social_media_share() to use generaly in theme folder. To define a custom template tag, simply write a PHP function and document it for Plugin users on your Plugin's home page and/or in the Plugin's main PHP file. It's a good idea when documenting the function to give an example of exactly what needs to be added to the theme file to use the function, including the and >.

Saving Plugin Data to the Database

Lots of time in plugin development we require to save input data from user to save it to database for use in its filter functions, action functions, and template functions. This information has to be saved in the WordPress database, in order to be persistent between sessions. There are four (4) methods for saving Plugin data in the database:

  1. Use the WordPress "option" mechanism (described below). This method is appropriate for storing relatively small amounts of relatively static, named pieces of data -- the type of data you'd expect the site owner to enter when first setting up the Plugin, and rarely change thereafter.
  2. Post Meta (a.k.a. Custom Fields). Appropriate for data associated with individual posts, pages, or attachments. See post_meta Function Examples, add_post_meta(), and related functions.
  3. Custom Taxonomy. For classifying posts or other objects like users and comments and/or for a user-editable name/value list of data consider using a Custom Taxonomy, especially when you want to access all posts/objects associated with a given taxonomy term. See Custom Taxonomies.
  4. Create a new, custom database table. This method is appropriate for data not associated with individual posts, pages, attachments, or comments -- the type of data that will grow as time goes on, and that doesn't have individual names. See Creating Tables with Plugins for information on how to do this.

WordPress Options Mechanism

To save all the option in your plugin autometically to database visit this page Creating Options PagesWordPress has a mechanism for saving, updating, and retrieving individual, named pieces of data ("options") in the WordPress database. Option values can be strings, arrays, or PHP objects (they will be "serialized", or converted to a string, before storage, and unserialized when retrieved). Option names are strings, and they must be unique, so that they do not conflict with either WordPress or other Plugins. It's also generally considered a good idea to minimize the number of options you use for your plugin. For example, instead of storing 10 different named options consider storing a serialized array of 10 elements as a single named option. Here are the main functions your Plugin can use to access WordPress options.
add_option($name, $value, $deprecated, $autoload);
Creates a new option; does nothing if option already exists.
$name
Required (string). Name of the option to be added.
$value
Optional (mixed), defaults to empty string. The option value to be stored.
$deprecated
Optional (string), no longer used by WordPress, You may pass an empty string or null to this argument if you wish to use the following $autoload parameter.
$autoload
Optional, defaults to 'yes' (enum: 'yes' or 'no'). If set to 'yes' the setting is automatically retrieved by the wp_load_alloptions function.
get_option($option);
Retrieves an option value from the database.
$option
Required (string). Name of the option whose value you want returned. You can find a list of the default options that are installed with WordPress at the Option Reference.
update_option($option_name, $newvalue);
Updates or creates an option value in the database (note that add_option does not have to be called if you do not want to use the $deprecated or $autoload parameters).
$option_name
Required (string). Name of the option to update.
$newvalue
Required. (string|array|object) The new value for the option.
 

Administration Panels

There ofcourse required plugin setting page where user can manage settings required to execute the plugin functionality ,for details visit Adding Administration Menus.

Top-Level Menus

If you have decided your plugin requires a brand-new top-level menu, the first thing you'll need to do is to create one with the add_menu_page function. Note: skip to Sub-Menus if you don't need a top-level menu. add_menu_page($page_title,$menu_title,$capability,$menu_slug,$function,$icon_url,$position);> Parameter values:
page_title
The text to be displayed in the title tags of the page when the menu is selected.
menu_title
The on-screen name text for the menu.
capability
The capability required for this menu to be displayed to the user. When using the Settings API to handle your form, you should use 'manage_options' here as the user won't be able to save options without it. User levels are deprecated and should not be used here!
menu_slug
The slug name to refer to this menu by (should be unique for this menu). Prior to Version 3.0 this was called the file (or handle) parameter. If the function parameter is omitted, the menu_slug should be the PHP file that handles the display of the menu page content.
function
The function that displays the page content for the menu page. Technically, the function parameter is optional, but if it is not supplied, then WordPress will basically assume that including the PHP file will generate the administration screen, without calling a function. The page-generating code can be written in a function within the main plugin file. In the event that the function parameter is specified, it is possible to use any string for the file parameter. This allows usage of pages such as ?page=my_super_plugin_page instead of ?page=my-super-plugin/admin-options.php.
The function must be referenced in one of two ways:
  1. if the function is a member of a class within the plugin it should be referenced as array( $this, 'function_name' )
  2. in all other cases, using the function name itself is sufficient
icon_url
The url to the icon to be used for this menu. This parameter is optional.
position
The position in the menu order this menu should appear. By default, if this parameter is omitted, the menu will appear at the bottom of the menu structure. To see the current menu positions, use print_r($GLOBALS['menu']) after the menu has loaded.

Sub-Level Menus

Once your top-level menu is defined, or you have chosen to use an existing WordPress top-level menu, you are ready to define one or more sub-level menu items using the add_submenu_page function. Make sure to add the sub-level menu items in the order you want them displayed.

Using add_submenu_page

add_submenu_page($parent_slug,$page_title,$menu_title,$capability,$menu_slug,$function);> Parameter values:
parent_slug
The slug name for the parent menu, or the file name of a standard WordPress admin file that supplies the top-level menu in which you want to insert your submenu, or your plugin file if this submenu is going into a custom top-level menu.
Examples:
  1. For Dashboard: add_submenu_page('index.php',...)
  2. For Posts: add_submenu_page('edit.php',...)
  3. For Media: add_submenu_page('upload.php',...)
  4. For Links: add_submenu_page('link-manager.php',...)
  5. For Pages: add_submenu_page('edit.php?post_type=page',...)
  6. For Comments: add_submenu_page('edit-comments.php',...)
  7. For Custom Post Types: add_submenu_page('edit.php?post_type=your_post_type',...)
  8. For Appearance: add_submenu_page('themes.php',...)
  9. For Plugins: add_submenu_page('plugins.php',...)
  10. For Users: add_submenu_page('users.php',...)
  11. For Tools: add_submenu_page('tools.php',...)
  12. For Settings: add_submenu_page('options-general.php',...)
page_title
Text that will go into the HTML page title for the page when the submenu is active.
menu_title
The text to be displayed in the title tags of the page when the menu is selected.
capability
The capability required for this menu to be displayed to the user. User levels are deprecated and should not be used here!
menu_slug
For existing WordPress menus, the PHP file that handles the display of the menu page content. For submenus of a custom top-level menu, a unique identifier for this sub-menu page.
In situations where a plugin is creating its own top-level menu, the first submenu will normally have the same link title as the top-level menu and hence the link will be duplicated. The duplicate link title can be avoided by calling the add_submenu_page function the first time with the parent_slug and menu_slug parameters being given the same value.
function
The function that displays the page content for the menu page.
Technically, as in the add_menu_page function, the function parameter is optional, but if it is not supplied, then WordPress will basically assume that including the PHP file will generate the administration screen, without calling a function. Most plugin authors choose to put the page-generating code in a function within their main plugin file.
In the event that the function parameter is specified, It's possible to use any string for the file parameter. This allows usage of pages such as ?page=my_super_plugin_page instead of ?page=my-super-plugin/admin-options.php.
See the Top-Level Menus for notes about how to reference class members as function parameters.
Example
Here's a quick example illustrating how to insert a top-level menu page and a sub-menu page, where the title on the sub-menu page is different from the top-level page. In this example, 'my_magic_function' is the name of the function that displays the first sub-menu page: add_menu_page('Pagetitle','Top-levelmenutitle','manage_options','my-top-level-handle','my_magic_function'); add_submenu_page('my-top-level-handle','Pagetitle','Sub-menutitle','manage_options','my-submenu-handle','my_magic_function'); > Here's an example of adding an option page under a custom post type menu block (see also here): add_submenu_page('edit.php?post_type=wiki','Options','Options','manage_options','wiki-options',array(&$this,'options_page'));>

Internationalizing Your Plugin

internationalization means you making your plugin in such a way that it easily translaeplugins display in other language. Internationalization is the process of setting up software so that it can be localized; localization is the process of translating text displayed by the software into different languages. WordPress is used all around the world, so it has internationalization and localization built into its structure, including localization of Plugins. Please note that language files for Plugins ARE NOT automatically loaded. Add this to the Plugin code to make sure the language file(s) are loaded:

	load_plugin_textdomain('your-unique-name', false, basename( dirname( __FILE__ ) ) . '/languages' );

To fetch a string simply use __('String name','your-unique-name'); to return the translation or _e('String name','your-unique-name'); to echo the translation. Translations will then go into your plugin's /languages folder. It is highly recommended that you internationalize your Plugin, so that users from different countries can localize it. There is a comprehensive reference on internationalization, including a section describing how to internationalize your plugin, at I18n for WordPress Developers.

The Right Way of Including Scripts

Now we are going to look at the right way of including scripts, considering the limitations in above technique. WordPress came up with a concept called action hooks which will be executed at specific points of a request or when a specific event occurs in your system. You can define a functions to be called in these execution points. It will take time to understand the complete concept of WordPress action hooks, even for an experienced WordPress developer. For the moment think of it as a code that calls PHP function at specific points. Consider the following code.

  
     function my_custom_function() {

// Place the code to be executed here } add_action('action name', 'my_custom_function'); We can replace the action name with predefined WordPress hooks or using our own custom hooks. You have to use different functions to different actions. In depth knowledge of action hooks will be provided in future tutorials when you get comfortable with basics of plugin development. Now let’s switch back to the correct method for including scripts. WordPress provides a predefined hook called wp_enqueue_scripts to include script files into pages. Inside our custom function we have to include the scripts one by one. Consider the following code.

add_action('wp_enqueue_scripts', 'fwds_scripts');
function fwds_scripts() {
  wp_enqueue_script('jquery');
  wp_register_script('slidesjs_core', plugins_url('js/jquery.slides.min.js', __FILE__),array("jquery"));
  wp_enqueue_script('slidesjs_core');
  wp_register_script('slidesjs_init', plugins_url('js/slidesjs.initialize.js', __FILE__));
  wp_enqueue_script('slidesjs_init');
}

Preceding code calls the fwds_scripts function in the execution process using the wp_enqueue_scripts action. I have used fwds(first web designer slider) as the prefix for my functions.

It is recommended to prefix your plugin functions with string related to your plugin name to avoid conflicts with functions in other plugins.

Inside fwds_scripts, we have used two other functions for including script files called wp_enqueue_script and wp_register_script. wp_enqueue_script is used to include the script file to the HTML document. jQuery is one of the libraries which comes in-built with WordPress and hence we can include it directly as shown in the code. Latest version of jQuery will be included in this technique. wp_register_script is used to register a script file into WordPress. We have to register the slider plugin file and initialization file since it is not built-in with WordPress. First parameter is a unique name to register your library. Next you have to provide the path of the js file. plugins_url function will provide the URL of the plugin folder.

The Right Way of Including Styles

Recommended method of including style files is exactly similar to the method we discussed for JavaScript files. wp_enqueue_scripts action will be used again with different function name to include the styles as shown in the following code.

 add_action('wp_enqueue_scripts', 'fwds_styles'); 
 function fwds_styles() { 
 wp_register_style('slidesjs_example', plugins_url('css/example.css', __FILE__)); 
 wp_enqueue_style('slidesjs_example'); 
 wp_register_style('slidesjs_fonts', plugins_url('css/font-awesome.min.css', __FILE__)); 
 wp_enqueue_style('slidesjs_fonts'); 
 }

We have to use wp_register_style and wp_enqueue_style in this case instead of script functions. Usage and parameters are exactly similar to script functions. In this part, we are using SlidesJS for implementing the slider plugin. SlidesJS comes up with two CSS files for styles neccessary for look and feel of the presentation and including fonts. Now we know the basics of including scripts and styles of the jQuery plugin inside the WordPress plugin. Generally we place the initialization code for a plugin, inline within script tags in static HTML files. With WordPress, it’s better to add it to an existing js file or include in a new js file and load using the recommended way.

Advanced Usage of Shortcodes

In the previous example, we used the most basic form of shortcode. We can also have attributes and content in shortcodes to add additional features. Consider the following shortcode with attributes and content.

[my_advanced_shortcode name="pawan" age="27"] Description about me [/my_advanced_shortcode]

  These types of shortcodes contain opening and closing shortcode tags. Information placed between the opening and closing tags is considered content and key-value pairs inside the opening tag is considered as attributes. Following code shows how we can extract these information inside the actual shortcode function.

 function my_advanced_shortcode_handler( $atts, $content = null ) {
   extract( shortcode_atts( array(
      'name' => 'rohan',
      'age' => '20'
      ), $atts ) );
   echo $name;
   echo $age;
   echo $content;
}

Content and attributes of the shortcodes will passed as the default parameters to shortcode function. We can directly use the content using the $content variable. Here you will get “Description about me” as the content. Handling attributes is not straightforward as content. We have to extract each attribute from the $attr array. We can use the extract function as shown here. We define all the attribute with the default values. If attributes are supplied with shortcodes, default value will be replaced by passes value. Finally you can access these attributes using $name and $age.