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

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

by therichpost
0 comments
How to get current logged in user using Wordpress Rest Api?

Hello guys, how are you? Welcome back on blog therichpost.com. To obtain information about the current logged-in user through the WordPress REST API, please follow the below logic guys.

$user_id = ""; //<- add this

add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
    $GLOBALS['user_id'] = get_current_user_id(); //<- add this

    // route url: domain.com/wp-json/mmw/v1/testing
    register_rest_route( 'mmw/v1', 'testing', array(
        'methods' => 'GET',
        'callback' => 'get_custom_users_data',
    ));
}
//Customize the callback to your liking
function get_custom_users_data(){
    return $GLOBALS['user_id']; //<- add this
}

Remember, for security reasons, direct use of admin credentials in scripts or applications is not recommended. Instead, use application passwords or OAuth tokens, which can be revoked if necessary.

Guys if you will have any kind of query then feel free to comment below.

Jassa

Thanks

You may also like

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.