building a wordpress plugin
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
WordPress Plugin
AUGUST 22, 2013
michael stowe
Building Your
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
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
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
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
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/
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/
The Plugin
wordpress.org/extend/plugins/trackable-social-share-icons/
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
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/
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
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 */
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.
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.'); }
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
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>";
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.
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(); }
FOREACH LOOP
WordPress standards dictate spacing after the statement
and before and after the conditions.
foreach ( $items as $item ) { process_item( $item ); }
SHORT TAGS
PHP Short Tags should never be used as they will not be
enabled in all PHP configurations.
<?php echo 'hello';?>
TRAILING SPACES
WordPress standards dictate that you should remove all
trailing spaces, such as the example below shows:
<?php echo 'hello';?>
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 ) );
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.
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 ); }
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.
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
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);
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');
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' );
_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');
/* … */ }
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);
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');
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'); } }
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' ); }
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); } }
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);
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');
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; /* … */
EXCERPT FUNCTION <?php
// Process Excerpts if enabled function _trackableshare_process_excerpt($content) { return _trackableshare_process($content,true); }
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!
WAIT? WHAT ABOUT
THE ADMIN PANEL?
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'); } }
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 );
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'); } }
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']); /* … */
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.
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!
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.
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!
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/
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
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…
CODE AVAILABLE AT: http://wordpress.org/extend/plugins/trackable-social-share-icons/
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