Darcy ClarkeDevelopment / Design / UX

Toggle Main Navigation

Jan 13, 2011

Using anonymous functions with WordPress' add_action

Posted in "development"

Many of my WordPress developer counterparts come from a long background of non-development related work. Most of which have only been introduced to PHP as a programming language in order to better understand how their WordPress site functions. With this in mind you tend to find a lot of redundancy and, in many cases, unnecessary function associations.

Not many PHP developers find good uses for anonymous functions but they do come in handy when we look at developing more complex WordPress solutions with do_action and add_action.

The do_action function in WordPress essentially pulls in all associated functions from add_action and calls them using the PHP function call_user_func. This function can use a reference to a function or an anonymous function. Using the later will look very familiar to you if you've ever done a lot of Javascript programming.

In most cases WordPress developers will create an unecessary function to reference in add_action like below:


add_action('example_action', 'example_function');

function example_function(){
    echo "Testing Example";
The proposed streamlined approach is to pass an anonymous function and cut down on the number of methods created:
<pre class="brush:php">`do_action('example_action');

add_action('example_action', function(){
    echo "Testing Example";

Hopefully this inspires more widespread use among the WordPress development community.