如何和何处实例化扩展WP_REST_CONTROLLER的自定义类



我有一个我创建的插件,我想使用WP REST API控制器模式来扩展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');
.
.

我创建了一个名为Server/Controlter的class a文件夹,其中My_ctrl.php文件使用了一个延伸WP_REST_CONTROLLER的类,该类看起来像

//server/controllers/my_ctrl.php

class items extends WP_REST_Controller {
    /**
    * Register the routes for the objects of the controller.
    */
     public function register_routes() {
       .....
     }
}

但是,我在Sublime Xdebuge调用堆栈中收到以下错误:

[致命错误]类'Myplugin wp_rest_controller'找不到

我不确定如何解决此问题,将文件放在我的自定义控制器的位置,在哪里创建自定义类的实例?

偶然发现了这一点,以为我会提供我的解决方案,以防其他人遇到这一点。

这个想法是通过不实例化,直到称为实际的rest_api_init挂钩来延迟 WP_REST_Controller的实例化。

代码示例:

add_action( 'rest_api_init', function () {
    require_once(plugin_dir_path(__FILE__) . '/VideoImageApi.php');
    VideoImageApi::instance()->register_routes();
});

从回调中注意require_once

我已努力解决问题,我检查了wp-content plugins文件夹,找不到 rest-api文件夹,尽管我在 wp-includes rest-api中找到了该文件夹,但似乎该文件夹将" WP REST API"集成到IN中核心不包括API可以暴露的所有类(仅包含3个PHP文件),因此不包括 wp-content plugins rest-api lib lib lib endpoints class-wp-rest-controller.php。我安装了" WP REST API"插件,并将其添加到WP-Content 插件中,现在我没有错误了。(这很奇怪,因为我不知道它何时被从项目中删除)

谢谢Dan您的评论确实帮助我重新检查所有内容并扫描了我的WordPress中包含的文件夹,并意识到插件缺失,并且文件夹 wp-includes rest-api不包含所有必要的类。

最新更新