Kamran Kamran - 1 month ago 15
reST (reStructuredText) Question

is_user_logged_in() return false even when logged in to WordPress?

I have a plugin that I created and I want to use the WP rest api controller pattern and 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 in folder called server/controllers and inside it my_ctrl.php file with a class that extends WP_REST_Controller that looks like this

<?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',
),
);
}


}

I am logged in and I am using cookie authentication with Nonce in my plugin.
when I run my code and debug it with sublime xdebug extension I can see that I indeed hit the end points routes but although I am logged it in the lines: "is_user_logged_in()" = (bool) 0 and therefore the function create_item_permissions_check return new WP_Error(....);and not true;

therefore my rest callback "create_item" is not invoked, I don't understand why is_user_logged_in() return false even when I am logged in.

Answer

The solution was to send the logged in user info to my custom class as a parameter to the constructor and then use the user data in the permission check function and other functions that needs the user info:

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;
  }

  .
  .
  .


}

And my plugin myplugin_register_endpoints looks as follows:

function myplugin_register_endpoints(){

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

now when I route to one of the URL's And hit the end points and the check permission is invoked with the needed user data. $this->loged_in!=1 when thew user is not logged in, otherwise the permission check returns true .

Comments