Hello I am new to WP and PHP, I am trying to create a class that takes (maybe) an array of arrays, then used to generate N° add_action for each array passed.
Example:
[
array(
"name" => "my_custom_action",
"cb" => "function(){return true;}"
)
]
This is the code I wrote until now.
class Actions {
public function __construct($actions){
$this->actions = $actions;
foreach($this->actions as $action){
add_action($action['name'], $action['cb']);
}
}
}
I was reading about the create_function()
method, but it's deprecated.
I would like to understand how to create multiple add_action with a single call basically, instead of writing every time the function and then add the action in the constructor.
I also found this: .anonymous.php
It's used to generate functions instead of using create_function()
, but I do not understand it very well.
Hello I am new to WP and PHP, I am trying to create a class that takes (maybe) an array of arrays, then used to generate N° add_action for each array passed.
Example:
[
array(
"name" => "my_custom_action",
"cb" => "function(){return true;}"
)
]
This is the code I wrote until now.
class Actions {
public function __construct($actions){
$this->actions = $actions;
foreach($this->actions as $action){
add_action($action['name'], $action['cb']);
}
}
}
I was reading about the create_function()
method, but it's deprecated.
I would like to understand how to create multiple add_action with a single call basically, instead of writing every time the function and then add the action in the constructor.
I also found this: https://www.php/manual/en/functions.anonymous.php
It's used to generate functions instead of using create_function()
, but I do not understand it very well.
1 Answer
Reset to default 1Check out the php callable manual.
A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
However, in your code sample you are using an anonymous function, which can be passed directly.
[
array(
"name" => "my_custom_action",
"cb" => function(){return true;}
)
]