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?
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.
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.
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();
In JavaScript, callbacks and anonymous functions can be used interchangeably.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With