Building a WordPress Plugin


Published on

Imagine if you had the ability to spread your brand across the WordPress platform! By building your own WordPress plugin you put your name, your company, and your offerings right in front of thousands of WordPress bloggers.

This presentation covers the basics of building a WordPress plugin from start to finish. Basic understanding of PHP necessary.

Published in: Technology, Business
1 Comment
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Building a WordPress Plugin

  1. 1. WordPress Plugin AUGUST 22, 2013 michael stowe Building Your
  2. 2. MIKESTOWE •  Open Source Contributor •  Author, Speaker, and Consultant •  10+ years experience hacking PHP •  Zend Certified PHP 5.3 Software Engineer •  Developer Advocate with Constant Contact .com @mikegstowe
  3. 3. WHAT IS WORDPRESS? Ok, seriously… what are you doing here? Or rather, where have you been living for the last 5 years? WordPress is a popular blogging system that has gone from a “share your thoughts” platform to being used as a platform for CMS, Ecommerce, and more! hosts over 375,500 bloggers! is a hosting service for WordPress blogs
  4. 4. WHAT ARE WORDPRESS PLUGINS? One of the most powerful features of WordPress is the ability to customize your “blog” with plugins. The WordPress community has contributed over 26,550 plugins, which have been downloaded over 504,052,000 times! is home to the WordPress Project
  5. 5. WHAT ARE WORDPRESS PLUGINS? Compare that to just a year ago when the WordPress community had only contributed approximately 20,000 plugins, which had been downloaded over 300,000,000 times! is home to the WordPress Project
  6. 6. WHAT CAN YOU DO WITH A WORDPRESS PLUGIN? There are WordPress plugins for just about everything, including SEO, comments, eCommerce, pictures, stats, social sharing, social communities, social media importing, data importing, RSS feeds, mobile, … Ok, I’m not going to list them all. Point is, yeah, you can do just about anything!
  7. 7. SO HOW DO YOU BUILD A WORDPRESS PLUGIN? That’s what we’re going to talk about! To do that, we’re going to take a look at a real, published WordPress plugin called “Trackable Social Media Icons.” I developed this plugin with Ecreativeworks to provide users with the ability to track social media shares with Google Analytics. Last I checked the plugin has over 64,000 downloads!
  8. 8. The Plugin
  9. 9. DEVELOPING A WORDPRESS PLUGIN •  Creating the Plugin File •  WordPress Coding Standards •  Activation and Uninstall Hooks •  Other Action Hooks •  Filter Hooks •  Adding Menus •  Adding Meta Boxes
  10. 10. THE PLUGIN FILE WordPress plugins are PHP scripts that are included within the WordPress blog once activated. WordPress parses the plugin information from the comments found at the top of the WordPress plugin in order to explain to users what your plugin is and what it does. These comments include the Plugin Name, Plugin URI, Description, Version, Author, Author URI, and License.
  11. 11. THE PLUGIN FILE To get started, we’ll create a new folder called trackable-social-share-icons or whatever you want to call your plugin. Inside of this folder we’ll create a file called trackable-social-share-icons.php which will be the master file for our WordPress plugin. We can put other files in this folder, but this is the one that will be run by WordPress. Now we add the descriptive comments. Note – index.php can also be used as a master file, but is not recommended
  12. 12. THE PLUGIN FILE <?php <?php       /*     Plugin  Name:  Trackable  Social  Share  Icons     Plugin  URI:­‐social-­‐share-­‐icons     Description:  The  Trackable  Social  Share  Icons  plugin  enables  blog  readers  to   easily  share  posts  via  social  media  networks,  including  Facebook  and  Twitter.  All   share  clicks  are  automatically  tracked  in  your  Google  Analytics.     Version:  1.3     Author:  Name:  Ecreative  Internet  Marketing     Author  URI:     License:  MIT     */  
  13. 13. THE PLUGIN FILE The next line of code we’ll add to the file is designed to prevent our plugin from being run outside of WordPress. In the case of another plugin, HTMLe, this snippet is modified to determine whether or not to turn the file into a WordPress plugin or render it individually. To do this, check to see if the constant WP_PLUGIN_DIR has been defined.
  14. 14. THE PLUGIN FILE <?php <?php       /*     Plugin  Name:  Trackable  Social  Share  Icons     Plugin  URI:­‐social-­‐share-­‐icons     Description:  The  Trackable  Social  Share  Icons  plugin  enables  blog  readers  to   easily  share  posts  via  social  media  networks,  including  Facebook  and  Twitter.  All   share  clicks  are  automatically  tracked  in  your  Google  Analytics.     Version:  1.3     Author:  Name:  Ecreative  Internet  Marketing     Author  URI:     License:  MIT     */       //  Make  Sure  it  is  a  WordPress  Blog              if  (!defined('WP_PLUGIN_DIR'))  {                      die('This  WordPress  plugin  is  not  supported  by  your  system.');                }  
  15. 15. CODING STANDARDS Now, before we get into the plugin too deep, we need to keep in mind WordPress’ Coding Standards. Since every plugin published on is open-source and publicly available, the coding standards are designed to make reading, understanding, and modifying the plugin code easier on developers of all levels. A full list of coding standards can be found at:
  16. 16. SINGLE DOUBLE QUOTES The general rule is use whichever does not need escaping, although single quotes are preferred. echo  '<a  href="/static/link"  title="Yeah  yeah!">Link  name</a>';   echo  "<a  href='$link'  title='$linktitle'>$linkname</a>";  
  17. 17. INDENTATION USE TABS Most coding standards say to use “4” spaces for tabs (for readability across different platforms and uniformity), however WordPress prefers tabs over spaced indentations.
  18. 18. IF ELSE SPACING WordPress standards dictate spacing after the statement and before and after the conditions. if  (  condition  )  {          action1();          action2();   }  elseif  (  condition2  &&  condition3  )  {          action3();          action4();   }  else  {          defaultaction();   }      
  19. 19. FOREACH LOOP WordPress standards dictate spacing after the statement and before and after the conditions. foreach  (  $items  as  $item  )  {          process_item(  $item  );   }    
  20. 20. SHORT TAGS PHP Short Tags should never be used as they will not be enabled in all PHP configurations. <?php  echo  'hello';?>    
  21. 21. TRAILING SPACES WordPress standards dictate that you should remove all trailing spaces, such as the example below shows: <?php  echo  'hello';?>    
  22. 22. FUNCTIONS When declaring or calling functions in WordPress Plugins, use the following convention: function  my_function(  $param1  =  'foo',  $param2  =  'bar'  )  {     /*  ...  */   }     my_function(  $param1,  func_param(  $param2  )  );  
  23. 23. NAMING CONVENTIONS Use lower case words with underscores for functions and classes, and hyphens for file names. For example: my-file.php function my_function() WordPress standards dictate you should not use camelCase.
  24. 24. YODA CONDITIONS Yoda Conditions are conditions that “seem” backwards. For example, rather than saying variable is true, we would say true variable is. This helps prevent accidental assignments (variable = true). if  (  true  ==  $the_force  ){      $victorious  =  you_will(  $be  );   }    
  25. 25. OK, BACK TO CODE Now that we have our basic plugin file, and a decent understanding of the coding standards we can continue to build our plugin. In order to have our plugin do different things within the WordPress Blog we will be using “hooks.” Hooks are essentially WordPress functions that tell WordPress what Plugin functions to call for specific actions.
  26. 26. HOOKS There are two types of hooks: Action Hooks: Hooks that call functions based on certain actions Filter Hooks: Hooks that are used to filter data or content
  27. 27. HOOK DYNAMIC To setup a hook, you call the specific hook (either add_action() or add_filter() and give it the action you want modified, as well as the function you want called back.   add_filter(ACTION,  CALLBACK_FUNCTION);  
  28. 28. OUR HOOKS <?php //  Activate  Hooks   register_activation_hook(  __FILE__,  '_trackableshare_activate'  );   register_sidebar_widget(__('Trackable  Social  Share  Icons'),     '_trackableshare_embed');     add_action('admin_menu',  '_trackableshare_menu');     add_action('admin_init',  '_trackableshare_add_custom_box',  1);   add_action('save_post',  '_trackableshare_save_box_postdata');     add_filter('the_content',  '_trackableshare_tag');   add_filter('the_content',  '_trackableshare_process');   if(get_option('_trackablesharebutton_excerpt')  ==  '1')  {     add_filter('the_excerpt',  '_trackableshare_process_excerpt');   }     add_filter('wp_head',  '_trackableshare_header');   add_filter('wp_footer',  '_trackableshare_footer');    
  29. 29. ACTIVATION HOOK Our first hook, register_activation_hook() is called when the plugin is activated from within the Admin Panel. In the Trackable Social Share Icons plugin we use that to setup the necessary variables. Let’s take a look at the _trackableshare_activate() function. register_activation_hook(  __FILE__,  '_trackableshare_activate'  );
  30. 30. _TRACKABLESHARE_ACTIVATE() <?php   //  Activation  Function   function  _trackableshare_activate()  {     add_option('_trackablesharebuttons',  'facebook,twitter,email');     add_option('_trackablesharebutton_additionalbuttons',  '');     add_option('_trackablesharebutton_type',  '1');     add_option('_trackablesharebutton_fblike',  'none');   add_option('_trackablesharebutton_fblike_faces',  'false');     add_option('_trackablesharebutton_fblike_send',  'true');     add_option('_trackablesharebutton_sharethis_text',  '');     add_option('_trackablesharebutton_text',  '0');     add_option('_trackablesharebutton_size',  '100%');     add_option('_trackablesharebutton_google',  '1');     add_option('_trackablesharebutton_excerpt',  '0');     add_option('_trackablesharebutton_page',  '1');     add_option('_trackablesharebutton_post',  '1');     add_option('_trackablesharebutton_hidehome','1');   /*  …  */   }    
  31. 31. ADD_OPTION() The add_option() function allows you to add a Key => Value paired Option to the WordPress options table. If the option already exists, the function does nothing. This makes it useful for installations and initial configurations.   add_option(KEY,  VALUE);  
  32. 32. ACTION HOOKS In our plugin we call three different action hooks. The first adds a menu item, the second adds a box to the Post/ Page Edit form, and the third we use when a Post/ Page is saved. add_action('admin_menu',  '_trackableshare_menu');     add_action('admin_init',  '_trackableshare_add_custom_box',  1);     add_action('save_post',  '_trackableshare_save_box_postdata');  
  33. 33. THE MENU FUNCTION <?php //  Menu  Function   function  _trackableshare_menu()  {     if(function_exists('add_submenu_page'))  {       add_submenu_page('plugins.php','Trackable  Sharing',         'Trackable  Sharing',  10,  'trackable_sharing',         '_trackableshare_admin');     }   }    
  34. 34. THE EDIT FUNCTION <?php //  Setup  Post/Page  Edit  Meta  Boxes   function  _trackableshare_add_custom_box()  {          add_meta_box(                    '_trackable_share_box',                  __(  'Trackable  Social  Share  Icon  Options',                    '_trackableshare_textdomain'  ),                  '_trackableshare_editpost',                  'post',  'normal',  'high'            );          add_meta_box(                    '_trackable_share_box',                  __(  'Trackable  Social  Share  Icon  Options',                    '_trackableshare_textdomain'  ),                  '_trackableshare_editpost',                  'page',  'normal',  'core'            );   }  
  35. 35. THE SAVE FUNCTION <?php //  Page  Edit  Admin  -­‐  SAVE   function  _trackableshare_save_box_postdata($id)  {     if(isset($_POST['_trackablesearch_hide']))  {       update_option('_trackablesharebutton_postid_'.$id.'_hide',1);     }  else  {       update_option('_trackablesharebutton_postid_'.$id.'_hide',0);     }   }  
  36. 36. UPDATE_OPTION() The update_option() function allows you to add or update a key=>value paired Option to the WordPress options table.   update_option(KEY,  VALUE);  
  37. 37. FILTER HOOKS In our plugin we call five different filter hooks: The first two add filters to the post/page content, the third to the post excerpt, and the last two to the header/ footer. add_filter('the_content',  '_trackableshare_tag');   add_filter('the_content',  '_trackableshare_process');   if(get_option('_trackablesharebutton_excerpt')  ==  '1')  {     add_filter('the_excerpt',  '_trackableshare_process_excerpt');   }     add_filter('wp_head',  '_trackableshare_header');   add_filter('wp_footer',  '_trackableshare_footer');  
  38. 38. CONTENT FUNCTION <?php //  Build  Buttons   function  _trackableshare_process($content,  $excerpt  =  false,  $page_url  =  false,   $page_title  =  false)  {     static  $fbjs  =  false;     static  $gplusjs  =  false;     global  $post;       if(get_option('_trackablesharebutton_page')  !==  false  &&  !$excerpt)  {         if($post-­‐>post_type  ==  'page')  {         if(get_option('_trackablesharebutton_page')  ==  '0')  {           return  $content;         }       }  else  {         if(get_option('_trackablesharebutton_post')  ==  '0')  {           return  $content;           /*  …  */  
  39. 39. EXCERPT FUNCTION <?php //  Process  Excerpts  if  enabled   function  _trackableshare_process_excerpt($content)  {     return  _trackableshare_process($content,true);   }  
  40. 40. HEADER/ FOOTER FUNCTIONS <?php //  Header  CSS   function  _trackableshare_header()  {     if(strlen(trim(get_option('_trackablesharebutton_header')))  >  0)  {       echo  '<style   type="text/css">'.get_option('_trackablesharebutton_header').'</style>';     }   }     //  Footer   function  _trackableshare_footer()  {     if(get_option('_trackablesharebutton_footer')  ==  '1')  {       /*  Echo  Credits  */   }   }   Credits must be DISABLED by default!
  42. 42. BACK TO THE MENU HOOK Remember our menu hook? Let’s take a closer look at that! Let’s take a look at the _trackableshare_activate() function. //  Menu  Function   function  _trackableshare_menu()  {     if(function_exists('add_submenu_page'))  {       add_submenu_page('plugins.php','Trackable  Sharing',         'Trackable  Sharing',  10,  'trackable_sharing',         '_trackableshare_admin');     }   }    
  43. 43. ADD_SUBMENU_PAGE() The add_submenu_page() function allows us to create a menu item that when clicked calls back our function: add_submenu_page(  $parent_slug,  $page_title,              $menu_title,  $capability,              $menu_slug,  $function  );  
  44. 44. BACK TO THE MENU HOOK Essentially, we are creating a new menu item under “Plugins”, called “Trackable Sharing”, the user privileges required for this link, and the function to call back. //  Menu  Function   function  _trackableshare_menu()  {     if(function_exists('add_submenu_page'))  {       add_submenu_page('plugins.php','Trackable  Sharing',         'Trackable  Sharing',  10,  'trackable_sharing',         '_trackableshare_admin');     }   }    
  45. 45. ADMIN FUNCTION <?php //  Admin  Panel   function  _trackableshare_admin()  {     //  Database  Update     if(isset($_POST['buttons']))  {       update_option('_trackablesharebuttons',  $_POST['buttons']);       update_option('_trackablesharebutton_additionalbuttons',   $_POST['additional']);       update_option('_trackablesharebutton_type',  $_POST['type']);       update_option('_trackablesharebutton_text',  $_POST['text']);       update_option('_trackablesharebutton_sharethis_text',   $_POST['sharethis_text']);       update_option('_trackablesharebutton_fblike',  $_POST['fblike']);       update_option('_trackablesharebutton_fblike_faces',   $_POST['fblike_faces']);       update_option('_trackablesharebutton_fblike_send',   $_POST['fblike_send']);       update_option('_trackablesharebutton_size',  $_POST['size']);       /*  …  */  
  46. 46. ADMIN FUNCTION The Admin Function contains all that’s necessary to display and handle the form. It’s the largest function in our plugin, which makes sense when it controls all the configurations possible for the trackable social share icons.
  47. 47. AND ON THE FRONT END With these functions and a few more we’re able to build the following social share icon configurations. WordPress hooks make this incredibly easy, and help us to build this highly flexible plugin in just over 600 lines of code!
  48. 48. PUBLISHING YOUR PLUGIN Now that you have your plugin built and ready to go, you’re probably going to want people to use it. The easiest way to do this is to add it to the WordPress Plugin Repository. To get started, create an account at if you do not already have one.
  49. 49. PUBLISHING YOUR PLUGIN Now go to the Developers Corner and click on “Add a Plugin.” Otherwise you can access it directly (after logging in) at: Fill in the required information, and will create an online repository for your Plugin!
  50. 50. USE SVN TO CHECKOUT AND COMMIT WordPress’ Plugin Repository utilizes SVN, so you’ll need to install SVN on your local machine in order to checkout the online repository, add your files, and commit the files back to WordPress. You can learn more about using SVN with your WordPress plugin here:
  51. 51. THE README FILE Creating a strong ReadMe file is vital to “selling” your plugin to others. Keep in mind, you can’t charge for your plugin AND host it on the WordPress Plugin Repository, but you still want to convince people to download it. Here is a good starter template for your ReadMe file:
  52. 52. OUR README text ===  Trackable  Social  Share  Icons  ===   Contributors:  EcreativeIM,  mikestowe   Tags:  social  media,  sharing,  trackable,  google  analytics,  facebook,  twitter,  social,   social  bookmarking,  email,  reddit,,  digg,  stats,  statistics,  share,   sharing,  tracking,  analytics,  snail  mail,  google  plus,  pinterest   Requires  at  least:  2.9   Tested  up  to:  3.3.1     The  Trackable  Social  Share  Icons  plugin  enables  blog  readers  to  easily  share  posts   via  social  media  networks,  including  Facebook  and  Twitter.  All  share  clicks  are   automatically  tracked  in  your  Google  Analytics.       ==  Description  ==     Increase  the  reach  of  your  blog  with  social  network  sharing,  and  track  the  number  of   share  clicks  in  Google  Analytics.     Trackable  Social  Share  Icons  plugin  is  a  simple,  intuitive,  and  customizable  plugin   that  places  social  media  icons,  such  as  Twitter  and  Facebook,  at  the  bottom  of…  
  54. 54. THANK YOU. @mikegstowe visit for more on PHP and Web Development @ctct_api A big thank you to Constant Contact for making this presentation possible