即使登录到WordPress,is_user_logged_in()也返回false?

时间:2016-06-20 20:09:04

标签: wordpress api rest controller wordpress-plugin

我有一个我创建的插件,我想使用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(&#39; rest_api_init&#39;&#39; myplugin_register_endpoints&#39);    。    

我在名为server / controllers的文件夹中创建了一个类,并在其中创建了一个my_ctrl.php文件,其中包含一个扩展WP_REST_Controller的类,如下所示

<?php

class items extends WP_REST_Controller {

  /**
  * Register the routes for the objects of the controller.
  */

  public function register_routes() {
    $version = '1';
    $namespace = 'my-namespase/v' . $version;
    $base = 'abc';

    register_rest_route( $namespace, '/' . $base, array(
        array(
            'methods'         => WP_REST_Server::READABLE,
            'callback'        => array( $this, 'get_items' ),
            'permission_callback' => array( $this, 'get_items_permissions_check' ),
            'args' => array(
                'id' => array(
                    'required' => true,
                    'validate_callback' => function($param, $request, $key) {
                        return is_numeric( $param ) and ! is_null(get_post($param));//numeric post id value and there is valid post for this id
                    },
                    'sanitize_calback' => 'absint'
                )
            ),
        ),

    ) );

    register_rest_route( $namespace, '/' . $base . '/(?P<id>[\d]+)', array(
        array(
            'methods'         => WP_REST_Server::CREATABLE,
            'callback'        => array( $this, 'create_item' ),
            'permission_callback' => array( $this, 'create_item_permissions_check' ),
            'args' => array(
                'id' => array(
                    'required' => true,
                    'validate_callback' => function($param, $request, $key) {
                        return is_numeric( $param ) and ! is_null(get_post($param));//numeric post id value and there is valid post for this id
                    },
                    'sanitize_calback' => 'absint'
                )
            ),
        ),
        array(
            'methods'  => WP_REST_Server::DELETABLE,
            'callback' => array( $this, 'delete_item' ),
            'permission_callback' => array( $this, 'delete_item_permissions_check' ),
            'args' => array(
                'id' => array(
                    'required' => true,
                    'validate_callback' => function($param, $request, $key) {
                        return is_numeric( $param ) and ! is_null(get_post($param));//numeric post id value and there is valid post for this id
                    },
                    'sanitize_calback' => 'absint'
                )
            ),
        ),
    ) );

    register_rest_route( $namespace, '/' . $base . '/schema', array(
        'methods'         => WP_REST_Server::READABLE,
        'callback'        => array( $this, 'get_public_item_schema' ),
    ) );

}

function get_items( $request ){
    return new WP_REST_Response( array('message' => "list items"), 200 );
}

function create_item( $request ) {
    .....
    if($author_email==$user_email) {

        return new WP_REST_Response( array('message' => 'success', 200 );

    } else {

       return new WP_Error('my-error', __(' error...','abc'), array( 'status' => 500 ));
    }
}

//Remove vote////////////////////////////////////////////
function delete_item( $request ) {
    ...
    if($author_email==$user_email) {

        return new WP_REST_Response( array('message' => 'success', 200 );

    } else {

       return new WP_Error('my-error', __(' error...','abc'), array( 'status' => 500 ));
  }

}

public function get_items_permissions_check( $request ) {
    return true;
}

public function create_item_permissions_check( $request ) {

    if ( !is_user_logged_in()) {
        return new WP_Error('login error',__('You are not logged in','KVotes-voting'));
    }
    return true;

}

public function delete_item_permissions_check( $request ) {
    return $this->create_item_permissions_check( $request );
}

protected function prepare_item_for_database( $request ) {
    return array();
}

public function prepare_item_for_response( $item, $request ) {
    return array();
}

public function get_collection_params() {
    return array(
        'page'                   => array(
            'description'        => 'Current page of the collection.',
            'type'               => 'integer',
            'default'            => 1,
            'sanitize_callback'  => 'absint',
        ),
        'per_page'               => array(
            'description'        => 'Maximum number of items to be returned in result set.',
            'type'               => 'integer',
            'default'            => 10,
            'sanitize_callback'  => 'absint',
        ),
        'search'                 => array(
            'description'        => 'Limit results to those matching a string.',
            'type'               => 'string',
            'sanitize_callback'  => 'sanitize_text_field',
        ),
    );
}

}

我已登录,并且我在插件中使用Nonce进行Cookie身份验证。 当我运行我的代码并使用sublime xdebug扩展调试它时,我可以看到我确实点击了终点路线但是我记录了它们的行:&#34; is_user_logged_in()&#34; =(bool)0因此函数create_item_permissions_check返回新的WP_Error(....);而不是true;

因此我的休息回调&#34; create_item&#34;没有被调用,我不明白为什么is_user_logged_in()即使在我登录时也会返回false。

2 个答案:

答案 0 :(得分:1)

解决方案是将登录的用户信息作为构造函数的参数发送到我的自定义类,然后在权限检查功能和需要用户信息的其他功能中使用用户数据:

class items extends WP_REST_Controller {

  /**
  * Register the routes for the objects of the controller.
  */
   private $loged_in;//bool
   private $user;
   public function __construct($logged,$cur_user) {
       = $logged;
    $this->user = $cur_user;
   }

   .
   .
   .

   public function create_item_permissions_check( $request ) {

       if($this->loged_in!=1){
           return new WP_Error('login error',__('You are not logged in','....'));
       }
       return true;
  }

  .
  .
  .


}

我的插件myplugin_register_endpoints如下所示:

函数myplugin_register_endpoints(){

   require_once 'server/controllers/my_ctrl.php';       
   $items=new items(is_user_logged_in(),wp_get_current_user());
   $items->register_routes();
}

现在,当我路由到其中一个URL时,点击终点并使用所需的用户数据调用检查权限。当用户未登录时,$ this-&gt; loged_in!= 1,否则权限检查返回true。

答案 1 :(得分:0)

我恰好遇到了这个问题。看来,解决该问题的体系结构正确方法是让ajax请求包含一个随机数。请参阅this answer

中讨论的参考资料