Should you use anonymous functions in WordPress actions and filters?

At their simplest, an anonymous function is an unnamed function. There are many ways they can be used to simplify your PHP – but when it comes to WordPress I’ve often wondered if it’s a good or a bad thing to use anonymous functions when adding an action or filter.

For example, a WordPress filter using an anonymous function would would look like

add_filter( 'gform_default_address_type', function ( $default_address_type, $form_id ) {
return 'us';
}, 10, 2 );

The alternative, using a named function, would look like

add_filter( 'gform_default_address_type', 'default_address_type', 10, 2 );
function default_address_type ( $default_address_type, $form_id )  {
return 'us';
}

So should you use anonymous functions with your actions and filters?

No – not unless you know what you’re doing an accept the disadvantages.

Whilst the WordPress Coding Standards guide does not touch on the topic, I have not seen one anonymous function in the whole WordPress core (interestingly in the JavaScript they do, just not in the PHP section).

Consistent coding style is critical with all software, but even more so with open source projects like WordPress. If WordPress core is not using them, I don’t think they have a place in plugins, themes or customisations.

Other good reasons are …

  • you won’t be able to remove the function using remove_action() or remove_filter()
  • the functions are unnamed and are therefore missing a key bit of documentation/context (the name) – developers tend to use the name to describe the purpose of the function
  • the functions cannot be used more than once
  • you need at least PHP version 5.3.0 – there is a surprisingly high number of cheap web hosts running websites on older versions of PHP