WordPress hooks can be used in two ways:
-
using callback function name and appropriate function
add_action( 'action_name', 'callback_function_name' ); function callback_function_name() { // do something }
-
using anonymous function (closure)
add_action( 'action_name', function() { // do something } );
Is there any difference for WordPress what way to use? What is prefered way and why?
The disadvantage of the anonymous function is that you’re not able to remove the action with remove_action.
Important: To remove a hook, the
$function_to_remove
and$priority
arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.Because you didn’t define
function_to_remove
, you can’t remove it.So you should never use this inside plugins or themes that somebody else might want to overwrite.
Using closures has the benefit of keeping the global namespace clean, because you don’t have to create a global function first to pass as a callback.
Personally I would prefer using closures as callbacks, unless:
Closures in Classes
Closures can also be beneficial within classes.
Normally callback methods need to be made public, but in this case you can also make them private or protected.
This solution only works for PHP 5.4+. To also make it work for PHP 5.3, you need to explicitly pass the
$this
object reference to the closure, like:Just to be more precise, I wanted to add this from the current wordpress docs; to actually demonstrate how this depends on a use-case:
“Why do we use a named function here [as callback of an ajax action hook] […]? Because closures are only recently supported by PHP. […] Since some people may still be running older versions of PHP, we always use named functions for maximum compatibility. If you have a recent PHP version and are developing only for your own installation, go ahead and use closures if you like.”
You can use in both these ways. But using anonymous functions has two major disadvantages,
remove_action()
andremove_filter()
needs the function name as a parameter and you don’t have it in this way.So, I would prefer using a named function.