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

Cover Image for How to get current logged in user using Wordpress Rest Api?
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

📝💡 How to Get Current Logged In User Using WordPress Rest Api?

Are you struggling to get the current logged in user using the WordPress Rest Api? Frustrated with getting unexpected results or facing errors? Don't worry, we've got you covered! In this blog post, we'll tackle this common issue and provide you with easy solutions. By the end, you'll be able to retrieve the current logged in user effortlessly.

The Problem

One of our readers, let's call him John, faced a similar problem while working on a custom WordPress Rest Api. John tried adding a custom request using the following code:

add_action('rest_api_init', function () {
    register_rest_route( 'custom', '/login', array(
        'methods' => 'GET',
        'callback' => function(WP_REST_Request $request) {
            return wp_get_current_user();
        }
    ));
});

The code always returned a user with an ID of 0, even though John was logged in. He also attempted another solution:

add_action('rest_api_init', function () {
    register_rest_route( 'custom', '/login', array(
        'methods' => 'GET',
        'callback' => function(WP_REST_Request $request) {
            return is_user_logged_in();
        }
    ));
});

Unfortunately, this approach always returned false, even when John was logged in. 😞

The Solution

After analyzing John's code and the issues he faced, we've come up with a solution to help you get the current logged in user using the WordPress Rest Api:

Solution 1: Check Authentication

To ensure that the user is logged in, you need to check the authentication status of the request. You can use the is_user_logged_in() function to achieve this. However, is_user_logged_in() won't work in the context of the Rest Api. Instead, you can utilize the rest_authentication_errors filter to achieve the desired result.

Here's how you can modify John's code to check for authentication:

add_action('rest_api_init', function () {
    register_rest_route( 'custom', '/login', array(
        'methods' => 'GET',
        'callback' => function(WP_REST_Request $request) {
            if (is_user_logged_in()) {
                return wp_get_current_user();
            } else {
                return new WP_Error( 'rest_not_logged_in', 'You are not logged in.', array( 'status' => 403 ) );
            }
        }
    ));
});

With this modification, if the user is logged in, you'll get the current logged in user. Otherwise, you'll receive a 403 status code along with an error message stating that you're not logged in.

Solution 2: Include Authentication Headers

To solve the issue of the rest_cookie_invalid_nonce error, you need to include the X-WP-Nonce header in your HTTP request. This header contains a specific nonce value that WordPress uses to verify the authenticity of the request.

Here's how you can modify John's code to include the X-WP-Nonce header:

add_action('rest_api_init', function () {
    register_rest_route( 'custom', '/login', array(
        'methods' => 'POST',
        'callback' => function(WP_REST_Request $request) {
            $nonce = $request->get_header('X-WP-Nonce');
            if (empty($nonce) || !wp_verify_nonce($nonce, 'wp_rest')) {
                return new WP_Error( 'rest_cookie_invalid_nonce', 'Cookie nonce is invalid', array( 'status' => 403 ) );
            }

            // Rest of the code
        }
    ));
});

Now, every request you make should include the X-WP-Nonce header for authentication. This will prevent the rest_cookie_invalid_nonce error from occurring.

Conclusion

Now that you have the solutions at your disposal, getting the current logged in user using the WordPress Rest Api should no longer be a hassle. Whether it's checking authentication or including the necessary headers, these solutions will help you retrieve the desired data effortlessly.

If you still face any issues or have any questions, feel free to leave a comment below. Happy coding! 😊


💌 Did you find this blog post helpful? If yes, share it with your fellow WordPress developers and help them overcome this common issue!

🗨️💬 We'd love to hear your thoughts and experiences with the WordPress Rest Api. Share your stories and any additional tips in the comments section below. Let's learn from each other and grow together!

✨ Stay tuned for more handy WordPress tutorials, tips, and tricks on our blog. Don't miss out on our future posts by subscribing to our newsletter. Stay connected and keep expanding your WordPress skills!


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello