I have a custom endpoint which looks like this:
add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
'methods' => 'GET',
'callback' => 'get_user_lang'
));
});
I was able to call the callback function "get_user_lang" when it wasn't a class based method. But once I converted it to a class based method, I wasn't able to call it.
My class looks like this:
<?php
namespace T2mchat\TokenHandler;
class TokenHandler {
function get_user_lang() {
return "client_langs";
}
}
?>
and my new endpoint looks like this:
$t2m = new T2mchat\TokenHandler\TokenHandler();
add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
'methods' => 'GET',
'callback' => array($t2m, 'get_user_lang')
));
});
Anyone have any idea on how to call a class based method in WordPress Rest API custom endpoints?
WordPress exposes many REST API endpoints (such as WP_REST_Posts_Controller ), but as discussed above all endpoints extend from a common base controller class: WP_REST_Controller: The base class for all WordPress core endpoints. This class is designed to represent a consistent pattern for manipulating WordPress resources.
This class is designed to represent a consistent pattern for manipulating WordPress resources. When interacting with an endpoint that implements WP_REST_Controller, a HTTP client can expect each endpoint to behave in a consistent way. Infrastructure classes support the endpoint classes.
To call the callback as a method, proceed as follows: class MyClass { static function myCallbackMethod () { echo 'Hello world!'; } } In PHP, callbacks are a popular way to have functions communicate with each other.
The other major advantage of classes is the way in which class inheritance lets you share logic between multiple endpoints. Our example class here did not extend any base class, but within WordPress core all endpoint controllers extend a single abstract controller class called WP_REST_Controller.
If the hook is called within the class if-self and yout callback method is defined there:
add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
'methods' => 'GET',
'callback' => array($this,'get_user_lang')
));
});
If from different class:
add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user_lang', array(
'methods' => 'GET',
'callback' => array(new className,'get_user_lang')
));
});
If this solution is not working, a bit more details of your problem will help in defining.
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