building a wordpress plugin

54
WordPress Plugin AUGUST 22, 2013 michael stowe Building Your

Upload: michael-stowe

Post on 08-May-2015

2.653 views

Category:

Technology


6 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: Building a WordPress Plugin

WordPress Plugin

AUGUST 22, 2013

michael stowe

Building Your

Page 2: Building a WordPress Plugin

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

Page 3: Building a WordPress Plugin

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!

WordPress.com hosts over 375,500 bloggers!

WordPress.com is a hosting service for WordPress blogs

Page 4: Building a WordPress Plugin

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!

WordPress.org is home to the WordPress Project

Page 5: Building a WordPress Plugin

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!

WordPress.org is home to the WordPress Project

Page 6: Building a WordPress Plugin

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!

wordpress.org/extend/plugins/

Page 7: Building a WordPress Plugin

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!

wordpress.org/extend/plugins/trackable-social-share-icons/

Page 8: Building a WordPress Plugin

The Plugin

wordpress.org/extend/plugins/trackable-social-share-icons/

Page 9: Building a WordPress Plugin

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

Page 10: Building a WordPress Plugin

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.

wordpress.org/extend/plugins/trackable-social-share-icons/

Page 11: Building a WordPress Plugin

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

Page 12: Building a WordPress Plugin

THE PLUGIN FILE <?php

<?php       /*     Plugin  Name:  Trackable  Social  Share  Icons     Plugin  URI:  http://www.ecreativeim.com/trackable-­‐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:  http://www.ecreativeim.com/     License:  MIT     */  

Page 13: Building a WordPress Plugin

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.

Page 14: Building a WordPress Plugin

THE PLUGIN FILE <?php

<?php       /*     Plugin  Name:  Trackable  Social  Share  Icons     Plugin  URI:  http://www.ecreativeim.com/trackable-­‐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:  http://www.ecreativeim.com/     License:  MIT     */       //  Make  Sure  it  is  a  WordPress  Blog              if  (!defined('WP_PLUGIN_DIR'))  {                      die('This  WordPress  plugin  is  not  supported  by  your  system.');                }  

Page 15: Building a WordPress Plugin

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 WordPress.org 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:

codex.wordpress.org/WordPress_Coding_Standards

Page 16: Building a WordPress Plugin

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>";  

Page 17: Building a WordPress Plugin

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.

Page 18: Building a WordPress Plugin

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();  }      

Page 19: Building a WordPress Plugin

FOREACH LOOP

WordPress standards dictate spacing after the statement

and before and after the conditions.

foreach  (  $items  as  $item  )  {          process_item(  $item  );  }    

Page 20: Building a WordPress Plugin

SHORT TAGS

PHP Short Tags should never be used as they will not be

enabled in all PHP configurations.

<?php  echo  'hello';?>    

Page 21: Building a WordPress Plugin

TRAILING SPACES

WordPress standards dictate that you should remove all

trailing spaces, such as the example below shows:

<?php  echo  'hello';?>    

Page 22: Building a WordPress Plugin

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  )  );  

Page 23: Building a WordPress Plugin

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.

Page 24: Building a WordPress Plugin

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  );  }    

Page 25: Building a WordPress Plugin

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.

Page 26: Building a WordPress Plugin

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

Page 27: Building a WordPress Plugin

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);  

Page 28: Building a WordPress Plugin

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');    

Page 29: Building a WordPress Plugin

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'  );

Page 30: Building a WordPress Plugin

_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');  

/*  …  */  }    

Page 31: Building a WordPress Plugin

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);  

Page 32: Building a WordPress Plugin

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');  

Page 33: Building a WordPress Plugin

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');     }  }    

Page 34: Building a WordPress Plugin

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'            );  }  

Page 35: Building a WordPress Plugin

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);     }  }  

Page 36: Building a WordPress Plugin

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);  

Page 37: Building a WordPress Plugin

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');  

Page 38: Building a WordPress Plugin

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;           /*  …  */  

Page 39: Building a WordPress Plugin

EXCERPT FUNCTION <?php

//  Process  Excerpts  if  enabled  function  _trackableshare_process_excerpt($content)  {     return  _trackableshare_process($content,true);  }  

Page 40: Building a WordPress Plugin

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!

Page 41: Building a WordPress Plugin

WAIT? WHAT ABOUT

THE ADMIN PANEL?

Page 42: Building a WordPress Plugin

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');     }  }    

Page 43: Building a WordPress Plugin

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  );  

Page 44: Building a WordPress Plugin

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');     }  }    

Page 45: Building a WordPress Plugin

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']);       /*  …  */  

Page 46: Building a WordPress Plugin

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.

Page 47: Building a WordPress Plugin

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!

Page 48: Building a WordPress Plugin

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 wordpress.org if you

do not already have one.

Page 49: Building a WordPress Plugin

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:

http://wordpress.org/extend/plugins/add/

Fill in the required information, and WordPress.org will

create an online repository for your Plugin!

Page 50: Building a WordPress Plugin

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:

http://wordpress.org/extend/plugins/about/svn/

Page 51: Building a WordPress Plugin

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:

http://wordpress.org/extend/plugins/about/readme.txt

Page 52: Building a WordPress Plugin

OUR README text

===  Trackable  Social  Share  Icons  ===  Contributors:  EcreativeIM,  mikestowe  Tags:  social  media,  sharing,  trackable,  google  analytics,  facebook,  twitter,  social,  social  bookmarking,  email,  reddit,  del.icio.us,  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…  

Page 53: Building a WordPress Plugin

CODE AVAILABLE AT: http://wordpress.org/extend/plugins/trackable-social-share-icons/

Page 54: Building a WordPress Plugin

THANK YOU.

@mikegstowe

visit mikestowe.com/slides for more on PHP and Web Development

@ctct_api

A big thank you to Constant Contact for making this presentation possible