Create your First WordPress Plugin

WordPress is the largest blogging platform available on the internet today; and with the official release of version three just around the corner, it’s only going to get bigger. As such, over the next few self-contained tuts, we’re going to learn the ins and outs of WordPress plugin development, starting with the creation of our first simple plugin, “Simple Optimization.”


Step 0 Before we Begin

This tutorial is going to assume that you have at least a beginner’s understanding of PHP and the WordPress syntax. Though we’ll be covering everything, some knowledge beforehand will help you grasp the concepts much more easily. I’ll also assumes that you have a WP blog setup and ready to go.

Step 1. What our Plugin Does

The very first step, when writing a WP plugin, is to determine everything you want it to do. Since this is our first plugin, we won’t do anything too drastic. Let’s create something which will speed up our blog; our pages will render faster, and we’ll also do a little SEO to improve our search rank and findability.
“Always create a list of what you want your plugin to actually do before you write any code!”

Remove useless meta tags:

  • “rsd_link” – Really Simple Discovery Link
  • “wlwmanifest_link” – Windows Live Writer link
  • “wp_generator” – WordPress version number

Remove unnecessary filters:

  • “wptexturize” – Curly quotes
  • “wp_filter_kses” – HTML in user profiles

SEO:

  • Insert post tags into <head> as keywords
  • Insert post excerpt into <head> as description

Step 2. Laying the Groundwork

To start, navigate to your plugins folder (“/wp-content/plugins/”), and create a new folder. We’ll call ours “simple-optimization.” Next, inside of this folder we’re going to need to create two files. The first will be the actual plugin file (named “main.php”), and the second will be the mandatory README (“readme.txt”). We’re going to leave readme.txt empty for the time being; so open main.php in your preferred text-editor and copy in the code below.
  1.     <?php  
  2. /* 
  3. Plugin Name: Name Of The Plugin 
  4. Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates 
  5. Description: A brief description of the Plugin. 
  6. Version: The Plugin's Version Number, e.g.: 1.0 
  7. Author: Name Of The Plugin Author 
  8. Author URI: http://URI_Of_The_Plugin_Author 
  9. License: A "Slug" license name e.g. GPL2 
  10. . 
  11. Any other notes about the plugin go here 
  12. . 
  13. */  
  14. ?>  
This text is the bare-bones minimum needed for a plugin to appear in the WordPress plugin directory. You’ll obviously need to fill each part as you see fit.

Step 3. Adding Features

The first two features we’re going to implement will also be the simplest. By default, WordPress adds several meta-tags to the <head> section of your blog, but the simple fact of the matter is that these meta-tags have absolutely no value at all; so we’re simply going to stop WordPress from adding them. Anytime WordPress performs an action, it’s either called a filter or an action, and we can either remove or manipulate these filters and actions (you can find a list of all the filters here, and all the actions here). In this case, we want to remove the various actions that add those meta-tags.
To do so, we use a very simple function called “remove_action(‘action’,'function’)”. This function will remove the function declared in the second parameter from the action, the first parameter.
  1. // Clean up wp_head  
  2. // Remove Really simple discovery link  
  3. remove_action('wp_head''rsd_link');  
  4. // Remove Windows Live Writer link  
  5. remove_action('wp_head''wlwmanifest_link');  
  6. // Remove the version number  
  7. remove_action('wp_head''wp_generator');  
The same exact same principle applies to the two filters we’re going to remove:
  1. // Remove curly quotes  
  2. remove_filter('the_content''wptexturize');  
  3. remove_filter('comment_text''wptexturize');  
  4. // Allow HTML in user profiles  
  5. remove_filter('pre_user_description''wp_filter_kses');  

Step 4. SEO

Now that we’ve cut out that bloat, let’s ensure our blog has some basic SEO; meaning, let’s make sure we have keywords per-page, which correspond to that page and change the description to match more with the article. For our keywords, we’re going to grab the tags of the current page/post. This is made super simple by the function “wp_get_post_tags()”. wp_get_post_tags will return an array of tags from the current post. We can then easily format this array into a string and place it within our header (inside the function “wp_head()”, that every theme should have in it already) by attaching our function to the wp_head action.
Let’s start out by creating a new function, tags_to_keywords(), and, inside of this function, we’ll write a simple if statement, which checks to see if the current page is a single post or page (using the WP functions: is_single() and is_page()). Next, we’ll create a variable inside this if statement, named $tags, and set its content to the function wp_get_post_tags(); however, in order for this function to work, we need to pass in a parameter of “post_id”. The easiest way for us to obtain that is to globalize the WP variable $post which contains the post ID ($post->ID, $post is an object which is why we’re calling its values like so).
  1. // SEO  
  2. // add tags as keywords  
  3. function tags_to_keywords(){  
  4.     global $post;  
  5.     if(is_single() || is_page()){  
  6.         $tags = wp_get_post_tags($post->ID);  
  7.     }  
  8. }  
Next, we’ll use a foreach to filter through the $tags data, and create a new array with only the information we want ($tag_array). Following that, we’ll implode the array into a string and separate each item from the array with a comma and space ($tag_string). Then, we’ll create another if statement that checks to see if $tag_string has a value (meaning, do we have any tags for the post) and if it does, echo out the final HTML.
  1. function tags_to_keywords(){  
  2.     global $post;  
  3.     if(is_single() || is_page()){  
  4.         $tags = wp_get_post_tags($post->ID);  
  5.         foreach($tags as $tag){  
  6.             $tag_array[] = $tag->name;  
  7.         }  
  8.         $tag_string = implode(', ',$tag_array);  
  9.         if($tag_string !== ''){  
  10.             echo "<meta name='keywords' content='".$tag_string."' />\r\n";  
  11.         }  
  12.     }  
  13. }  
The last thing we need to do now is attach our new function with the wp_head action. To do this, we’re going to call add_action(‘action’,'function’), and pass it the parameters “wp_head” and “tags_to_keywords” (in that order).
  1. add_action('wp_head','tags_to_keywords');  
To further increase our SEO, we’re going to add our description meta-data to the header as well, using the same method as the keywords. Once we have the if statement rewritten, we’re going to create a new variable $all_post_content and fill it using the WP function wp_get_single_post() (and pass the parameter of $post->ID). This will give us an object full of all the data about our post. With this variable, we can create a description using the actual content of the post, but we’re going to shorten it down to one hundred characters using the function substr ($excerpt). And then, we’ll just echo out the HTML with the excerpt written in. (Optionally, you can also add an else statement, and echo your blog description using the function get_bloginfo(‘description’).)
  1. // add except as description  
  2. function excerpt_to_description(){  
  3.     global $post;  
  4.     if(is_single() || is_page()){  
  5.         $all_post_content = wp_get_single_post($post->ID);  
  6.         $excerpt = substr($all_post_content->post_content, 0, 100).' [...]';  
  7.         echo "<meta name='description' content='".$excerpt."' />\r\n";  
  8.     }  
  9.     else{  
  10.         echo "<meta name='description' content='".get_bloginfo('description')."' />\r\n";  
  11.     }  
  12. }  
  13. add_action('wp_head','excerpt_to_description');  

Step 5. Optimizing the Database

The final feature for our plugin is going to optimize our database tables by removing overhead (useless/excess data in a SQL table created by manipulating the database). To begin, we’ll create a new function (optimize_database), and inside of it, we’re going to call the global WPDB variable ($wpdb). That way, we can interact with the database, without having to re-enter our authentication details. $wpdb has several methods you can use to interact with and retrieve information from the database (Full list here), but we’re only going to be using one, get_results. Using get_results with the parameters of “SHOW TABLES” and “ARRAY_A” will return to us an associative array of all the table names in the database. At that point, we can use a foreach to loop through each of the array values (using array_values to get the table name, because of how it’s layered by the function) and use another $wpdb method, query to run the optimize command (“OPTIMIZE TABLE _____”).
  1. //Optimize Database  
  2. function optimize_database(){  
  3.     global $wpdb;  
  4.     $all_tables = $wpdb->get_results('SHOW TABLES',ARRAY_A);  
  5.     foreach ($all_tables as $tables){  
  6.         $table = array_values($tables);  
  7.         $wpdb->query("OPTIMIZE TABLE ".$table[0]);  
  8.     }  
  9. }  
While this function works, it will never actually run because WordPress has no way to know to run it. Luckily, WordPress has a feature called cron, which schedules functions to run at specific intervals (daily, weekly, etc…); this is perfect for us, since we want to frequently optimize our database. To use Cron, we’re going to create a new function (simple_optimization_cron_on), and fill it with another function call to wp_schedule_event(). To work, wp_schedule_event needs three things: a time to run, an interval between each run, and a function to call; so we’ll pass it the parameters: ‘time()’ (we’ll assume that whenever the cron event is created is a good time to call the function), ‘daily’, ‘optimize_database’ in that order.
  1. function simple_optimization_cron_on(){  
  2.     wp_schedule_event(time(), 'daily''optimize_database');  
  3. }  
Great, now we have our optimize_database function being added to the WP cron list, or we would if we were to call the simple_optimization_cron_on function. It’s really unsafe and is a bad practice to call your own event addition functions, because through some arbitrary system of events, it could cause the function to be called multiple times. WordPress happens to have a set of specific hooks for plugins to solve this problem: register_activation_hook and register_deactivation_hook. These functions are called when a plugin is turned on (activated) and turned off (deactivated). This way, our cron function can only be added once. Now, we have the ability to remove the cron event if the plugin stops being used. To work, these functions need two pieces of information: the url to the file that has the activation and deactivation functions (99% of the time “__FILE__” will work perfectly here), and the name of the activation and deactivation function. We’ll also create a new function (simple_optimization_cron_off), and fill it with a call to another function (wp_clear_scheduled_hook(‘optimize_database’)) to delete our cron event.
  1. function simple_optimization_cron_off(){  
  2.     wp_clear_scheduled_hook('optimize_database');  
  3. }  
  4. register_activation_hook(__FILE__,'simple_optimization_cron_on');  
  5. register_deactivation_hook(__FILE__,'simple_optimization_cron_off');  

Step 6. Filling out the ReadMe

The last thing we need to do for our new plugin is fill in the readme.txt file. The readme.txt file is used by the WordPress Plugin directory to display all the information you provide it about your plugin. The best way to learn how to write an effective readme.txt file is to download the default from WP, and alter it accordingly to fit your plugin. Since ours was so simplistic, this is what I personally ended up with:
  1. === Simple Optimization ===  
  2. Contributors: Jonathan Wolfe  
  3. Plugin link: http://net.tutsplus.com/  
  4. Tags: simple, optimization, keywords, tags, description, SEO, optimize, database  
  5. Requires at least: 2.5.1  
  6. Tested up to: 2.9.2  
  7. Stable tag: trunk  
  8. Silently adds several optimizing functions to the WordPress back-end to make your blog 
  9.  or site run faster.  
  10. == Description ==  
  11. Simple Optimization adds several functions to WordPress that help trim the fat from
  12.  the system and also clean
  13.  up after itself a little bit all leading to a faster loading time for your blog or website.  
  14. **Features**  
  15. _Remove useless meta tags:_  
  16. "rsd_link" - Really Simple Discovery Link  
  17. "wlwmanifest_link" - Windows Live Writer link  
  18. "wp_generator" - WordPress version number  
  19. _Remove useless filters:_  
  20. "wptexturize" - currly quotes  
  21. "wp_filter_kses" - HTML in user profiles  
  22. _SEO:_  
  23. * Insert post tags into <head> as keywords  
  24. _Routinely optimize the database_  
  25.   
  26. == Installation ==  
  27. 1. Download, unzip and upload to your WordPress plugins directory  
  28. 2. activate the plugin within you WordPress Administration  

That’s it!

You just successfully wrote your first WordPress plugin, which is working and ready for the WP Plugins Directory. Along the way, you learned about filters and actions, using WP global objects, a lot about the WordPress nomencalture, how to interact with the database, cron events, and activation/deactivation hooks. If you have any questions, please leave a comment and I’ll respond as soon as I can.

The final code:

  1. <?php  
  2. /* 
  3. Plugin Name: Simple Optimization 
  4. Plugin URI: http://net.tutsplus.com 
  5. Description: A super-simple plugin to improve your blog 
  6. Version: 1.0 
  7. Author: Jonathan Wolfe 
  8. Author URI: http://fire-studios.com 
  9. License: GPL2 
  10. . 
  11. This plugin written for NETTUTS at http://net.tutsplus.com 
  12. . 
  13. */  
  14. // Clean up wp_head  
  15. // Remove Really simple discovery link  
  16. remove_action('wp_head''rsd_link');  
  17. // Remove Windows Live Writer link  
  18. remove_action('wp_head''wlwmanifest_link');  
  19. // Remove the version number  
  20. remove_action('wp_head''wp_generator');  
  21. // Remove curly quotes  
  22. remove_filter('the_content''wptexturize');  
  23. remove_filter('comment_text''wptexturize');  
  24. // Allow HTML in user profiles  
  25. remove_filter('pre_user_description''wp_filter_kses');  
  26. // SEO  
  27. // add tags as keywords  
  28. function tags_to_keywords(){  
  29.     global $post// Get access to the $post object  
  30.     if(is_single() || is_page()){ // only run on posts or pages  
  31.         $tags = wp_get_post_tags($post->ID); // get post tags  
  32.         foreach($tags as $tag){ // loop through each tag  
  33.             $tag_array[] = $tag->name; // create new array with only tag names  
  34.         }  
  35.         $tag_string = implode(', ',$tag_array); // convert array into comma seperated string  
  36.         if($tag_string !== ''){ // it we have tags  
  37.             echo "<meta name='keywords' content='".$tag_string."' />\r\n"// add meta tag to <head>  
  38.         }  
  39.     }  
  40. }  
  41. add_action('wp_head','tags_to_keywords'); // Add tags_to_keywords to wp_head function  
  42. // add except as description  
  43. function excerpt_to_description(){  
  44.     global $post// get access to the $post object  
  45.     if(is_single() || is_page()){ // only run on posts or pages  
  46.         $all_post_content = wp_get_single_post($post->ID); // get all content from the post/page  
  47.         $excerpt = substr($all_post_content->post_content, 0, 100).' [...]'// get first 100 characters 
  48. and append "[...]" to the end  
  49.         echo "<meta name='description' content='".$excerpt."' />\r\n"// add meta tag to <head>  
  50.     }  
  51.     else// only run if not a post or page  
  52.         echo "<meta name='description' content='".get_bloginfo('description')."' />\r\n"; // add 
  53. meta tag to <head>  
  54.     }  
  55. }  
  56. add_action('wp_head','excerpt_to_description'); // add excerpt_to_description to wp_head 
  57. function  
  58. //Optimize Database  
  59. function optimize_database(){  
  60.     global $wpdb// get access to $wpdb object  
  61.     $all_tables = $wpdb->get_results('SHOW TABLES',ARRAY_A); // get all table names  
  62.     foreach ($all_tables as $tables){ // loop through every table name  
  63.         $table = array_values($tables); // get table name out of array  
  64.         $wpdb->query("OPTIMIZE TABLE ".$table[0]); // run the optimize SQL command 
  65. on the table  
  66.     }  
  67. }  
  68. function simple_optimization_cron_on(){  
  69.     wp_schedule_event(time(), 'daily''optimize_database'); // rdd optimize_database to wp cron
  70.  events  
  71. }  
  72. function simple_optimization_cron_off(){  
  73.     wp_clear_scheduled_hook('optimize_database'); // remove optimize_database from wp cron
  74.  events  
  75. }  
  76. register_activation_hook(__FILE__,'simple_optimization_cron_on'); // 
  77. run simple_optimization_cron_on at plugin activation  
  78. register_deactivation_hook(__FILE__,'simple_optimization_cron_off'); // 
  79. run simple_optimization_cron_off at plugin deactivation  
  80. ?> 

1 comment:

  1. This site and this post very help full for all visitor any can get help by read this content and site.

    Or any body can get more help this wp web design site.

    ReplyDelete