在类库中注册休息路线不起作用

use*_*970 3 wordpress wp-api

我在构建WP插件时遇到了两个问题,问题是我想使用WP Rest API并通过自己的端点对其进行扩展。

我正在使用类对象编写代码,我注册了add_action('rest_api_init'我遇到的问题是端点现在正在路由中显示。

这是初始化插件时的代码。

class ThorAdmin {

    public function __construct() {

        // Activation and deactivation hook.
        register_activation_hook(WP_PLUGIN_DIR . '/wp-thor-fcm/wp-thor-fcm.php',  array($this, 'thor_fcm_activate'));
        register_deactivation_hook( WP_PLUGIN_DIR . '/wp-thor-fcm/wp-thor-fcm.php',  array($this, 'thor_fcm_deactivate' ));

        // Admin Menu
        add_action('admin_menu', array($this, 'thor_admin_menu'));
        add_action('admin_init', array($this, 'thor_fcm_settings_init'));

        add_action('wpmu_new_blog',  array($this, 'thor_on_new_blog', 10, 6));      
        add_action('activate_blog',  array($this, 'thor_on_new_blog', 10, 6));

        add_action('admin_enqueue_scripts', array($this, 'thor_head') );            

        //The Following registers an api route with multiple parameters. 
        add_action('rest_api_init', array($this, 'add_thor_fcm_route'));

        add_filter('admin_footer_text', array($this, 'thor_fcm_admin_footer'));
    }
Run Code Online (Sandbox Code Playgroud)

这是我从add_action('rest_api_init',array($ this,'add_thor_fcm_route'))调用的函数;

/**
 * Registers the routes for all and single options
 *
 */
function add_thor_fcm_route() {

    register_rest_route( 'wp/v2/thorfcmapi', '/options', array(
        'methods' => 'GET',
        'callback' => array ($this, 'add_fcm_option_route')
    ) );
}

/**
 * The callback for the `wp/v2/thorfcmapi/options` endpoint
 */
function add_fcm_option_route( WP_REST_Request $request ) {
    if($request['option']) {
        return get_field($request['option'], 'option');
    }

    return get_fields('option');
}
Run Code Online (Sandbox Code Playgroud)

当我执行此命令时,将其添加到我的网址中

 ?rest_route=/
Run Code Online (Sandbox Code Playgroud)

我在路由列表中找不到我的路由wp / v2 / thorfcmapi

如果我使用相同的代码,请仅使用此代码制作一个单独的插件

 add_action('rest_api_init', 'add_thor_FCM_Route_test' );

 function add_thor_FCM_Route_test() {
    register_rest_route( 'wp/v2/thorfcmapi', '/options', array(
       'methods' => GET,
       'callback' => 'add_FCM_Option_Route_test'
  ) );
}

/**
* The callback for the `wp/v2/thorfcmapi/options` endpoint
*/
function add_FCM_Option_Route_test( WP_REST_Request $request ) {
  if($request['option']) {
    return get_field($request['option'], 'option');
 }

   return get_fields('option');
Run Code Online (Sandbox Code Playgroud)

}

唯一的不同是,我不嵌入类中,也不使用$ this,它可以作为路由注册。我可以进行API调用。

我不想插入插件,我想让代码在我的类中起作用-我将简化的代码添加到了我的插件中(第一个示例),我首先在类外部添加了它,但仍然没有注册路由,并且没有错误。

我究竟做错了什么?

我似乎不了解要使它起作用是什么。

use*_*970 5

我发现了问题-它与使用is_admin()有关-如果is_admin为true,则无法注册休息路线。案件结案。