Anonymous Functions for Actions and Filters

Actions

Instead of using actions like this:

add_action('my_hook', 'do_something');
function do_something($value)
{
    return $value;
}

you can use anonymous functions like this:

add_action('my_hook', function($value)
{
    return $value;
});

While it’s maybe easier to use, you have two disadvantages:

  • You can’t remove an action by using remove_action when the action is added with an anonymous function
  • You can’t reuse your anonymous function. If you want to add your anonymous function twice (for two different hooks), you have to enter them twice.

Filters

Same for filters, instead of using filters like this:

add_filter('my_filter', 'do_something');
function do_something($value)
{
    return $value;
}

you can also use an anonymous function:

add_filter('my_filter', function($value)
{
    return $value;
});