Anonymous functions in WordPress hooks

Aleksandr Levashov picture Aleksandr Levashov · Jul 6, 2015 · Viewed 11.1k times · Source

WordPress hooks can be used in two ways:

  1. using callback function name and appropriate function

    add_action( 'action_name', 'callback_function_name' );
    function callback_function_name() {
        // do something
    }
    
  2. 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?

Answer

TeeDeJee picture TeeDeJee · Jul 6, 2015

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.