WordPress Hooks and jQuery Custom Events

WordPress Hooks

If you develop with WordPress, you’re very familiar with the Plugins API. This allows you to ‘hook’ into most any part of the application and either filter data or run bits of code at a desired sequence point.

A sample action hook might look like this:

add_action('init', 'foobar_register_post_type', 0);
function foobar_register_post_type(){
    //Do something
}

A sample filter hook might look like this:

add_filter('query_vars', 'foobar_add_public_query_var', 0, 1);
function foobar_add_public_query_var($vars){
    $vars[] = 'foobar_var';
    return $vars;
}

There are hundreds of way to extend WordPress which is why it’s an amazing application upon which to develop. You can even create your own custom hooks using something like the following:

do_action('foobar_action');
$data = apply_filters('foobar_filter', $data);

This gives others access to extend your code with a couple lines of code in the right spots.

jQuery Custom Events

Many WordPress developers are building nice front-end experiences these days on jQuery (JavaScript). More specifically, plugins and themes are using AJAX instead of using native $_POST or $_GET behavior. The problem I’ve run into with several plugins is their lack of front-end extensibility.

On the server-side, the proper WordPress hooks usually exist, but there’s typically no way to extend specific events on the client-side. jQuery gives us the ability to easily follow the pattern of WordPress hooks.

A simple custom event might like this:

//This is similar to the WP function add_action();
jQuery(document).bind('foobar_custom_event', function(event, param1, param2){
    //Do something
});

The way to trigger a custom event is as follows:

//This is similar to the WP function do_action();
jQuery(document).trigger('foobar_custom_event', {arg1 : ['foo', 'bar', 'hello', 'world'], arg2 : 'Hello World' });

As you can see we trigger ‘foobar_custom_event’ and pass in arguments to the callback. If you build plugins or themes for WordPress, it’s as simple as that to make your client-side scripts as extensible as your server-side scripts.

An example use-case would be to allow other plugins to hook into a form submission success state to pass the submitted data onto a third-party API or post it their own registered ‘wp_ajax’ hooks.

There’s no need for building out a complex hook system in JavaScript. It’s already available to you. It’s up to you to make your application as open as possible to cultivate creativity around your codebase.

Comments are closed.