I am trying to create a custom REST API endpoint in WordPress using Classes. I've also done the same the traditional way - which worked just fine. However, using classes I am getting an error The handler for the route is invalid
.
The code:
class CSS_Ads {
var $url;
var $endpointPrefix;
var $endpointName;
public function __construct()
{
add_action('rest_api_init', array( $this, 'ads_api_route' ) );
}
public function ads_api_route() {
register_rest_route( $this->endpointPrefix, $this->endpointName,
array(
'methods' => 'GET',
'callback' => 'get_all_ads_api_endpoint'
)
);
}
public function get_all_ads_api_endpoint($params) {
// doing my post query and stuff
}
}
Setting:
$ads = new CSS_Ads();
$ads->url = get_site_url();
$ads->endpointPrefix = 'bs/v1';
$ads->endpointName = 'ads';
Full error:
{"code":"rest_invalid_handler","message":"The handler for the route is invalid","data":{"status":500}}
The query is set to -1, there is only one post on the website so it shouldn't matter.
The problem here is that the callback is not reaching the function.
Solved the issue with the extra function below:
public function __construct()
{
// Add custom REST API endpoint
add_action('rest_api_init', __NAMESPACE__ . '\\ads_api_route' );
}
// REST API route
public function ads_api_route() {
register_rest_route( 'my_endpoint/v1', '/ads',
array(
'methods' => 'GET',
'callback' => [$this, 'get_all_ads_api_endpoint']
)
);
}
function init_rest_api_endpoint() {
$endpoint = new restAPIendpoint();
$endpoint->ads_api_route();
}
add_action( 'rest_api_init', 'init_rest_api_endpoint' );
Hope this helps someone in future :)