1

I can't get WP-API to show the current logged-in username for some reason it just shows an id : 0 and some other data.

functions.php

add_action( 'plugins_loaded', 'get_user_info' );

function get_user_info(){
    global $current_user;
    get_currentuserinfo();

    return $current_user;
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'cala', '/get', array(
        'methods' => 'GET',
        'callback' => 'get_user_info',
    ) );
} );

JSON

{
  "data": {

  },
  "ID": 0,
  "caps": [

  ],
  "cap_key": null,
  "roles": [

  ],
  "allcaps": [

  ],
  "filter": null
}

I am not sure if this is the best way either. Please help thanks.

Raymond the Developer
  • 1,576
  • 5
  • 26
  • 57

1 Answers1

-3

Id "0" means the current user is logged out (visitor). Check you session status when you are firing the request.

Try wp_get_current_user() or get_current_user_id() maybe it will work better for you.

user3127632
  • 375
  • 1
  • 5
  • 20
  • Just tried it still not working. $current_user does work when I use var_dump inside a template page. Just not in functions.php and getting it with WP-API. – Raymond the Developer Apr 30 '16 at 19:57
  • 1
    this answer is wrong, it does not work. It seems nothing related to the global user is initialized at the time when rest_api_init hook fires... i have not found any way of solving this. – mcartur Jan 13 '17 at 09:45
  • I agree with mcartur. Logged-in user is not accessible at the time when register_rest_route is called within the registered action for rest_api_init – justadev Feb 16 '17 at 21:11