WordPress Hooks Without Seperate Callbacks

Josh Pollock - April 16, 2014

Why is the feature image for this post about WordPress hook callback functions a cute elephant? Why the hell not? http://joshpress.net/?p=775Why is the feature image for this post about WordPress hook callback functions a cute elephant? Why the hell not? http://joshpress.net/?p=775

I’m working on a new starter theme for mobile-friendly WordPress-based web apps. I added two slide-out sidebars using Foundation’s offcanvas component. Inside of each is a menu, and a widget area. I wanted to make each of the two slide-outs, as well as the elements inside of them optional, so I wrapped each in a check if a filter, whose default value is true, is true. Testing this led me to using WordPress’ built-in utility functions like __return_false() as callbacks for filters and actions.

The usual pattern for adding WordPress hooks is to use the add_action() or add_filter() function to define which hook you are using and specify a callback function, which you then declare. This is the common pattern:

add_action( 'wp_head', 'slug_header_script' );
function slug_header_script() {
echo 'a script or text or something';
}

That’s fine, but there are some actions and filters, like the ones in my new theme whose parameters are simply true or false. For these there is no need to declare a new function just to set a variable to false. WordPress already includes several utility functions for setting hooks true, false, null, an empty string or an empty array.

For example, look at how we can use __return_true() to turn this:
add_filter( 'example_filter', 'slug_make_filter_true' );
function slug_make_filter_true( $param ) {
$param = true;
return $param;
}

Into this:
add_action( 'example_action', '__return_true') ;

That’s not just easier, but it makes your code more readable. That line of code is not only shorter, it’s easier to understand what it does.

I’m working on a new starter theme for

Here is a complete list of each of these functions: