I'm trying to call add_action from another function in this way:
Using this:
$this->add_action('most-rated', 'get_most_rated');
Instead of this:
add_action('rest_api_init', function () {
register_rest_route('app-api', 'most-rated', [
'methods' => 'GET',
'callback' => [$this, 'get_most_rated'],
]);
}, 10);
Where add_action is:
public function add_action($route, $endpoint, $request = 'GET') {
add_action('rest_api_init', function () {
register_rest_route('app-api', $route, [
'methods' => $request,
'callback' => [$this, $endpoint],
]);
}, 10);
}
The code is working and not sending any errors as the code after it is still being called, but the EndPoint isn't being added.
Am I doing something wrong that I should be aware of?
$route
, $endpoint
and $request
are not in the scope of the anonymous function, you can add a use
statement for accessing them inside the function.
public function add_action($route, $endpoint, $request = 'GET') {
add_action('rest_api_init', function () use ($route, $endpoint, $request) {
register_rest_route('app-api', $route, [
'methods' => $request,
'callback' => [$this, $endpoint],
]);
}, 10);
}