2016-12-04 63 views
2

我在構建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')); 
    } 

這裏是我從ADD_ACTION調用函數( 'rest_api_init',陣列($此, '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'); 
} 

當我做這個命令添加編輯我的網址

?rest_route=/ 

我不覺得在路線

列表我的路線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'); 

}

唯一不同的是,我沒有嵌入到一個類中,我不使用$ this,它的工作原理是註冊爲路由。我可以做一個API調用。

我不想插件,我想在我的課程中使用代碼 - 我將簡化代碼添加到我的插件中(第一個示例),我在課程之外首先添加了它,但它仍未註冊路線和沒有錯誤。

我在做什麼錯?

這是什麼,我似乎不明白,使其工作。

回答

0

我發現問題 - 它與使用is_admin()有關 - 如果is_admin爲true,我無法註冊休息路由。案件結案。