In a custom REST API method, I would like to identify the user (typically get_current_user_id() then retrieve their data from database (things like they're role and some custom permission).

But so far get_current_user_id() returns 0 (which is not the current user ID).

Is it possible to identify user in REST API?

Otherwise, a solution I see is using a page as "sort of" API ... but I think that would be an ugly solution.


I spent two days searching for a simple way without adding plugins.

first in function.php where you define your api

//enqueue the script which will use the api
function api_callings_scripts() {
    wp_enqueue_script('score-script', get_template_directory_uri() . '/js/ScoreSaving.js', ['jquery'], NULL, TRUE);
    // Pass nonce to JS.
    wp_localize_script('score-script', 'ScoreSettings', [
      'nonce' => wp_create_nonce('wp_rest'),
add_action( 'wp_enqueue_scripts', 'api_callings_scripts' ); 

Then your script Ajax call cloud be something like this

      type: "POST",
      url: "/wp-json/score/update",
      data: {"var1":"value1"},
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-WP-Nonce', ScoreSettings.nonce);
        function( data ) {
          console.log( data );

Now you can use get_current_user_id() inside your API code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.