Like the blog? Get the book »

Precision Targeting with Custom Action Hooks

Precision Targeting with Custom Action Hooks

WordPress’ powerful action-hook system makes it possible to insert functionality at any point in your theme. Most WordPress themes include some of the built-in WordPress hooks by default. For example, most of us are aware of the two most common WordPress hooks: wp_head() and wp_footer(), which generally appear in the theme’s header and footer sections. These two hooks provide WordPress a location at which to execute various scripts and functions. For example, the wp_head() hook is where WordPress generates a variety of <link> and <script> elements, among other things.

See hooks in action

To see this functionality in action, check out the source code of one of your web pages when the wp_head() hook is present in your header.php file (as it should be by default). Then remove the hook, reload the page, and check the source again. You will see that it is the wp_head() hook that enables those markup-generating functions to operate as intended.

Getting precise with custom hooks

In a similar vein, other areas of your theme may also be targeted with WordPress hooks. We have already mentioned the wp_footer() hook, which is useful for adding scripts, copyright information, and database statistics to the bottom of your pages. Indeed, you can apply targeted functionality to any of the currently available WordPress hooks, but many times it’s just as easy to create your own hook and place it exactly where you need it. Whether you are writing a plugin or implementing some custom functions.php goodness, custom hooks enable precision targeting anywhere within your theme, making it more flexible and easier to customize. Let’s look at an example..

An example of how custom hooks are used

At Perishable Press, I provide my guests with nearly twenty alternate themes that may used while visiting the site. Each of these themes is visually and functionally unique, requiring different sets of plugins and custom scripts in order to function properly. To get the plugins to play nice together and target only select groups of themes, I take advantage of WordPress’ custom-hook functionality. For example, I have a stats plugin that needs to hook into wp_head() for a few of my themes, but using that specific hook would result in conflicting scripts in some of the other themes. Thus, I added a custom hook in the header of the themes that require the stat plugin’s functionality. Other themes are not affected and everything clicks along like clockwork.

Creating and using custom hooks

Creating and using custom hooks is surprisingly simple. You basically need to define the hook in your functions.php (or plugin) file, and then place the hook tag in the desired location within your theme. Thus:

Step 1: Define your custom hook

Add this to your functions.php file:

// i can has custom hook
function custom_hook() {
	do_action('custom_hook');
}

This will add an action named “custom_hook” to WordPress’ hook library, enabling you to use it anywhere in your theme template. Of course, you should name your custom hook something that makes sense for your particular application. Once that is in place, move on to the next step.

Step 2: Tag your custom hook

Place the function call in the desired location within your theme template:

<?php custom_hook(); ?>

That’s all there is to it. With those two snippets of code in place, your theme is equipped with a custom hook through which you may execute any function you wish using WordPress’ powerful add_action() feature.

Step 3: Add your function

To keep things simple, we’ll use a very basic function to illustrate this step. In your functions.php file, add the following code:

<?php 
function hello_wordpress() {
	echo '<h1>Hello WordPress!</h1>';
}
add_action('custom_hook', 'hello_wordpress', 7);
?>

This function will echo “Hello WordPress!” on your web page at the location of your custom_hook() in your theme template. To really get a sense of how WordPress hooks work, try moving the <?php custom_hook(); ?> tag to a different location within your theme and watch the output text move accordingly. Amazing, but true.

The key to using your custom hook for one of your functions is this line:

add_action('custom_hook', 'hello_wordpress', 7);

This is where you actually associate your function with the custom hook. The first parameter is the name of the custom hook, the second parameter is the name of the function, and the third parameter sets the priority of the function. When multiple functions are targeting the same hook, the priority specifies the order in which the action should be performed. The default priority value is 10.

Take-home message

If nothing else, just remember that WordPress action hooks provide a way for you to output content virtually anywhere in your theme. Chances are that there is already a default hook that will do the job, but if not, the information in this tutorial will enable you to create and use custom hooks to get the job done.

That does it for this fine DiW tutorial. Be sure to subscribe to our feed for more great WordPress content delivered fresh to your feed reader!

11 responses

  1. Great! This is the best tut on Action Hooks I’ve ever seen!
    Defining Action Hooks this way is damn easy! Some time ago I created a wp framework, I used “if function exists” in php :|
    Thanks Jeff!

  2. I’d like to point out that adding a custom wrapping function like that is really not needed.

    Just insert into your theme.

    The main benefit of this, is that as fellow coders, we can see theres a hook RIGHT THERE, no mysterious functions to follow.

    The other benefit is that plugin authors who will eventually follow your example, do the same.. Well.. Then when someone uses a theme that doesnt have the plugin enabled, all hell breaks loose. However, Had you have used do_action(‘custom_action’) instead of custom_action_wrapper(), everything would’ve been fine…….

    Yes, Using a custom “Tag” (Its a function, -ok-?) does make things look more inline with the rest of the theme, but it has its downsides.

    (Also, Note, Theme authors, please make sure your functions are UNIQUE, say, name them _custom_function(), not my_action_hook(), Another bad plugin developer will come along and use it too, believe me).

    Sorry for the rantish comment..

  3. Interesting way of working. Keeps themes also nice and clean.

  4. I don’t get it. the only advantage with the hooks method seems to me that I can associate multiple functions to ONE hook, but why not call multiple functions within one other function and then call this other function within the template? this way I can actually see what the order is instead of juggling with numbers. I’m new to wordpress and have never developed a theme before but I’m quite familiar with php so … again I don’t get it =)

    • Of course, there is always a better way of doing something if you know how. This tutorial is aimed more at beginners and those unfamiliar with PHP. Just showing how easy it is to output content and run scripts with built-in WordPress functionality. That’s all, really. If you know of a better way, by all means use it.

      • Sorry, I didn’t mean to question the tutorial at all. I just wasn’t sure if I got the functionalities of hooks right. With “I don’t get it” I didn’t mean “hey this solution is bad, mine is better” I literally didn’t get it.
        keep it up! =)

      • Hey it’s all good. Sometimes it’s difficult to measure tone through written text, but I see now where you are coming from. There are so many ways to do things with WordPress, and it is always good to hear new ideas. =)

  5. @mizwo – Perhaps the best argument for the use of actions and filters in WordPress theme and plugin development is extensibility.

    If a theme uses only function calls in it’s template files, it is impossible to make customizations without directly editing the source where the function was defined – most likely in functions.php.

    If, however, the theme defines custom actions and filters and uses these in the template files, it is easy to overwrite the core functions of the theme without directly editing the function definitions.

    You can define a new function and apply it to the custom action or filter thus adding your customizations without touching the source of the theme.

    In the event that the theme becomes outdated and you need to upgrade, your functions will not be overwritten.

    Hope this helps to explain.

Comments are closed for this post. Contact us with any critical information.
© 2009–2024 Digging Into WordPress Powered by WordPress Monzilla Media shapeSpace