WP Ref

Using Anonymous Functions for Testing Hooks

There are times when you just want to try some code for a hook, but can’t be bother to write a separate function or class method. This can certainly be the case for myself when I’m working with a class with many methods, or a long file.

Trying It Out

Let’s say we want to echo a prettified array of posts onto every page (which you can learn more about in my guide, “Using var_export to Debug and Prettify Dumps of Anything“). We can write the following:

add_action( 'init', function() { $posts = get_posts(); echo '<pre>' . var_dump( $posts ) . '</pre>'; });
Code language: PHP (php)

Rather than referencing a callback with an array in the case of a class method or string in the case of a function, you can just write the function inline. You can of course access any arguments sent from do_action or apply_filters by specifying them as parameters, just as you can in a usual class method or function callback.

In Conclusion

Anonymous functions can be a great asset when utilized correctly. It’s a good idea to shy away from them when writing production code, however. For debugging or wanting to try something out with a hook, anonymous functions can be a convenient way to test some functionality out.





Need WordPress development services?


Leave a Reply

Your email address will not be published. Required fields are marked *