Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous functions in WordPress hooks

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?

like image 453
Aleksandr Levashov Avatar asked Jul 06 '15 07:07

Aleksandr Levashov


People also ask

What is an anonymous function and when should you use it?

Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function.

What are anonymous functions good for?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.

What is anonymous function with example?

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();

Can you use an anonymous function in a callback?

In JavaScript, callbacks and anonymous functions can be used interchangeably.


Video Answer


1 Answers

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.

like image 123
TeeDeJee Avatar answered Sep 28 '22 03:09

TeeDeJee