How to get current logged in user using Wordpress Rest Api?

后端 未结 5 1937
盖世英雄少女心
盖世英雄少女心 2020-12-25 11:32

I tried to add a custom request.

add_action(\'rest_api_init\', function () {
    register_rest_route( \'custom\', \'/login\', array(
        \'methods\' =>         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-25 12:05

    1. Install and activate JWT Authentication for WP REST API plugin, also install WP REST API plugin
    2. Now you can run any wordpress default api from mobile app or any other source or by postman. for example hit this url from your app or by postman. https://example.com/wp-json/wp/v2/posts
    3. By app or by postman, When you will login with valid details (using rest api) you will get back a token. To login and get token, run the following url by postman or by app https://example.com/wp-json/jwt-auth/v1/token
    4. By this way you will get a token as shown in picture
    Now use this token to get logged in user details, for example
    5. make function in function.php

    function checkloggedinuser()
    {
    $currentuserid_fromjwt = get_current_user_id();
    print_r($currentuserid_fromjwt);
    exit;
    }
    
     add_action('rest_api_init', function ()
    {
      register_rest_route( 'testone', 'loggedinuser',array(
      'methods' => 'POST',
      'callback' => 'checkloggedinuser'
      ));
    }); 
    

    6. Now again run this new url in postman or in app to get logged in user details. https://example.com/wp-json/testone/loggedinuser (replace example.com with your url) (https://i.stack.imgur.com/tIqhS.png)
    7. Also edit your .htaccess file and wp-config.php file according to instructions on pt.wordpress.org/plugins/jwt-authentication-for-wp-rest-api

提交回复
热议问题