Themergency

Make Your WordPress Plugins Extensible

Sometimes see your plugins being used in the strangest ways. Ways that you never intended it to be used when you initially designed the plugin. It is a good feeling to have, when you see your plugin being used and making customers happy. It gives a great sense of accomplishment. But you can make it even easier for your customers to alter the way your plugin works. All without touching a single line of code in the original plugin, after it has been released.

It all comes down to how you write the plugin and where you provide “hooks” so that it can be extended or changed. There are many plugins that do this already: WooCommerce and Easy Digital Downloads are great examples. The very fact that they have craploads of extensions, tells you that they are very extensible. This is how they do it:

Actions and Filters

Everything you need to know about actions and filters you can read up about on the Codex.

Actions

An action is a PHP function that runs at a very specific time. In a nutshell, actions allow you to “inject” code in between existing code without having to alter the original code. For example, you have some code that publishes a post on your blog, you could “hook” into the save_post action and send an email to all subscribers. You could do this with the following code:

add_action( 'save_post', 'send_awesome_emails_to_the_people' );

So why not allow for the same type of extensibility from your own plugins? For example, your cart plugin processes a discount code. Fire off an action after the code has been applied:

do_action( 'discount_code_applied', $discount_code );

Someone can now write a plugin that hooks into that action and logs each time the discount is applied:

function log_discount_code_usage($discount_code) {
   //do something here with $discount_code
}
add_action( 'discount_code_applied', 'log_discount_code_usage' );

Filters

Actions allow you to run code at specific times. Filters allow you to alter or even replace existing data. So in your plugin scenario, you declare an array of names that you show in a dropdown. Instead of just returning your array, rather wrap the result with apply_filters, for example:

$array = array(
   'Name 1' => 'Bob',
   'Name 2' => 'Jon'
};
return apply_filters('awesome_names', $array);

And then in a separate plugin, you can hook into that filter and add a third name:

function add_third_awesome_name($names) {
    $names['Name 3'] = 'Susan';
}
add_filter('awesome_names', 'add_third_awesome_name');

A Few Actions and Filters Go a Long Way

I hope you can see just how easy this is to do. With very little code, you can make your plugins extremely extensible. It could save you stacks of time from a support point of view, and not to mention, it will keep your plugin lean.

Do not build every new feature your users may suggest. Rather tell them to extend your plugin with their very own extension