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?
Advertisement
Answer
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.