Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress wp_get_current_user data not displaying in jason-api

I want to display a WordPress logged in user ID and email in another website so, I'm using the wordpressjson-api plugin to create an api but it's not working.
When I hit a direct link, it displays data as:

"{\"id\":1,\"email\":\"[email protected]\"}" 

But when I use json_decode and print data, it displays:

string(22) "{"id":0,"email":false}"

api code

public function get_loggedin_user_details() {
    global $user;
    global $wpdb, $json_api;
    $current_user = wp_get_current_user();
    $myObj->id = $current_user->ID;
    $myObj->email = $current_user->user_email;
    $logedin_userid = json_encode($myObj);
    return $logedin_userid;
  }
like image 706
Aman Naithani Avatar asked Mar 07 '26 02:03

Aman Naithani


1 Answers

Here the process to get the logged in user id on WP:

  1. install JWT Authentication for WP REST API plugin for rest-API authentication(read plugin description) enter image description here
  2. pass the login token you receive from the plugin to the route you created as Header: Authorization enter image description here

  3. create you custom Rest-API Route like this:

    add_action( 'rest_api_init', function () {
    register_rest_route( 'your_custom_route/v2', '/(?P<slug>[a-zA-Z0-9-]+)', array(
        'methods' => 'POST',
        'callback' => 'rest_api_custom_func',
        ) );
    } );
    
    function rest_api_custom_func(){ 
        global $user;
        global $wpdb;
        $current_user = wp_get_current_user();
        $myObj->id = $current_user->ID;
        $myObj->email = $current_user->user_email;
        $logedin_userid = json_encode($myObj);
        return $logedin_userid;     }
    
  4. write your own function as a callback function on rest-api route :rest_api_custom_func

  5. you can do whatever you want with your custom callback function

note: no need for any other plugin, use the built-in Wordpress Rest API

like image 135
Khalil DaNish Avatar answered Mar 08 '26 15:03

Khalil DaNish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!