Function Documentation

WordPress Function Documentation Progress

Writing Plugins: Getting the Current Hook

WordPress 2.5 adds the ability to get the current hook name. This is useful for when you have a function for a filter which needs to return different output by the hook name.

A little bit of History

I didn’t agree with the idea, but the patch put forward was clean and neat. The implementation really moves the progress of the WordPress 2.5 Plugin API forward. The reasoning behind the implementation is that there are several times where a single function needs to be used for different hooks but still do somewhat different things depending on each hook.

My suggestion was to create two functions for each hook, but after some time debating I eventually supported the idea. While I didn’t supply the patch, or at least not the patch that was committed to core, I do think debating the idea made for a better feature.

How to get the Current Hook

The current hook can be retrieved using the current_filter() function. It will return a string that has the name of the hook within the context of the function that is called within the hook.

To further explain, lets say that Hook_A has three functions and the second function calls Hook_B, which has one function. When the one function in Hook_B calls current_filter(), it will return ‘Hook_B’. When the three functions in Hook_A call current_filter(), it will return ‘Hook_A’.

It will always be this way since, PHP does not do multithreading to allow for current_filter() to process two hooks at the same time. So it can always be assumed that the value in current_filter() will always return the current filter that the function was hooked into.

Example Plugin

The example plugin strips tags in the ‘wp_title’ hook and in the ‘wp_content’ hook, but also calls wpautop for ‘wp_content’ hook.

add_filter('wp_title', 'myplugin_sanitize');
add_filter('wp_content', 'myplugin_sanitize');

function myplugin_sanitize($content) {
    $content = strip_tags($content);

    if( 'wp_content' == current_filter() )
        $content = wpautop($content);

    return $content;

So we reduced what would be two functions into one and reduced the footprint of the total plugin code.

For filtering it is useful to sanitize something for everything except for a few areas or allow for different hooks to have different allowable items, but not for others. While it is possible to write several functions for each one, it is better (arguably) to have everything in one function for maintainability.


January 11, 2008 Posted by | Writing Plugins Series | , , | Leave a comment