I have a plugin that I created and I want to use the WP rest api controller pattern in order to extend the api.
<?php
/**
* Plugin Name: myplugin
* Plugin URI: h...
* Description: A simple plugin ...
* Version: 0.1
* Author: Kamran ...
* Author ....
* License: GPL2
function myplugin_register_endpoints(){
require_once 'server/controllers/my_ctrl.php';
$items=new items();
$items->register_routes();
}
add_action('rest_api_init','myplugin_register_endpoints');
.
.
I created a class a folder called server/controllers and inside it my_ctrl.php file with a class that extends WP_REST_Controller that looks like this
// server/controllers/my_ctrl.php
class items extends WP_REST_Controller {
/**
* Register the routes for the objects of the controller.
*/
public function register_routes() {
.....
}
}
However I am receiving the following error in sublime xdebuge call stack:
[Fatal error] Class ‘mypluginWP_REST_Controller’ not found
I am not sure how to solve this issue, where to put the files for my custom controller, where to create the instance of the custom class etc?
Stumbled upon this and thought I’d provide my solution in case someone else encounters this.
The idea is to postpone the instantiation of the class extending
WP_REST_Controller
by not instantiating it until the actualrest_api_init
hook is called.Code example:
Note the
require_once
from within the callback.I have manged to solve the issue,
I checked the wp-contentplugins folder and I couldn’t find the rest-api folder and although I found the folder inside wp-includesrest-api it seems that this folder that integrates the “wp rest api” into core doesn’t include all the classes that the api can expose (it includes only 3 php files), So it didn’t include wp-contentpluginsrest-apilibendpointsclass-wp-rest-controller.php . I installed the “wp rest api” plugin and it was added to wp-contentplugins and now I don’t have the error anymore. (It was strange because I don’t know when it was deleted from my project)
Thank you Dan your comments really helped me to recheck everything and scan the folders included in my wordpress and realize that the plugin is missing and that the folder wp-includesrest-api doesnt contain all the needed classes.