Using Class/method callbacks for WordPress actions, filters, and shortcodes

When you wish to add functionality to WordPress – either in a theme or in a plugin, usually you hook into an action, a filter, or a shortcode. In other words, you’re telling WordPress “When such-and-such happens, please use this function here that I’m going to provide as a callback.” If you’re a developer, you understand all of this already. On the other hand, if you’re new to the realm of extending WordPress, you’re probably still working at fully appreciate this concept.

Now here’s the thing with the callbacks: WordPress has a zillion functions, and they’re always adding new ones. Developers are strongly advised to prefix their function names with something unique, in order to avoid function-name collisions with built-in functions that exist now, or may in the future. Here’s an example of using prefixes to hook into the add_action and add_shortcode functions:

add_action('wp_head', 'ysmt_wp_head');
add_shortcode('my_slider', 'ysmt_my_slider');
function ysmt_wp_head(){ /* do stuff */ }
function ysmt_my_slider(){ /* do stuff */ }

Now this can get messy, for a number of reasons, for starters I’d say that grouping related functions into a class improves readability, at the very least; and also, I’d say that prefixes suck. Its just extra typing, and I think it confuses things more than needed. And so a very reasonable alternative to the pattern shown above is to use classes & methods for your callbacks. Here’s an example:

$Ysmt = new Ysmt();
add_action('wp_head', array($Ysmt, 'wp_head'));
add_shortcode('my_slider', array($Ysmt, 'my_slider'));
class Ysmt{
function my_widget(){ /* do stuff */ }
function my_slider(){ /* do stuff */ }

Now in a way, you could say that this is actually an even longer way to prefix the callback names! However, I’d say that it can lead to code that’s more sane, and more readable over the long term, even if it’s maybe a bit uglier/longer than just adding a prefix. There’s another advantage lying in the fact that when you instantiate the $Ysmt object, you have the ability obviously to pass in parameters to a class constructor, and also there’s the fact that you’re using a single, shared instance of $Ysmt for these hooks. (Important to note that, your particular needs might require these objects to NOT be shared, obviously you’d want to structure your code accordingly.)

So bottom line is that using PHP classes and methods for WordPress callbacks is very easy, and can lead to nicer-looking code. For more info, check out the following resources:

  • WordPress Codex: add_action (As reference point on using callbacks in WordPress, the concept is applicable also to add_shortcode and add_filter.)
  • PHP Callbacks (Reference point on using class/methods for callbacks)