Background
I am trying to write Rest API code to get the ID of the user who triggers the function in question. I found a fantastic answer to this exact question, that was very kindly provided by user leymaxx: https://wordpress.stackexchange.com/a/329992/220571
Problem and Theories of Cause
However, when I test this code (by sending a Get request to my endpoint, using Postman), it always returns 0 when I call get_current_user_id(). I cannot figure out why it is doing this, but I have three theories:
- I may have implemented this wrong. That is, although the answer provided code, it did not explain exactly where it should be placed. I also needed to add some boilerplate such as declaring a plugin. I think I have worked this out, but I could be mistaken.
- The Rest API may have changed since the answer was posted. The question was from 2 years ago, so possibly there has been some subtle syntactical change due to an update.
- The API may not be able to detect that I am logged in. My website is in maintenance mode, so perhaps this prevents the API from detecting that I am logged in. I logged in by clicking "Visit Site" from my WordPress Dashboard, and confirmed this worked by viewing the My Account page from within my site.
Question
If anyone has any ideas of where I have gone wrong, please would you let me know? If so I would very much appreciate it, and I believe that having a fully detailed answer would also help other developers who encounter this common requirement.
The details of my overall approach, and the complete code that I used are given below.
Overall Approach
The steps I took were as follows:
- I created a new folder in the following location within my file management system: public_html/wp-content/plugins/example-plugin.
- In this folder I created two files: example-plugin.php and example-script.js.
- The code contained in these two files is shown below, and is basically identical to the above mentioned answer.
Code Used
The contents of example-plugin.php are as follows:
<?php
/**
* Plugin Name: Example Plugin
* Plugin URI: https://www.example.com/
* Description: Example Description.
* Version: 1.0
* Author: John Smith
* Author URI: https://www.example.com/
**/
class MyPlugin {
public function __construct() {
add_action('wp_enqueue_scripts', [$this, 'scripts']);
add_action('rest_api_init', [$this, 'rest']);
}
function scripts() {
// Add JS.
wp_enqueue_script('my-plugin', 'http://www.example.com/wp-content/plugins/example-plugin/example-script.js', ['jquery'], NULL, TRUE);
// Pass nonce to JS.
wp_localize_script('my-plugin', 'MyPluginSettings', [
'nonce' => wp_create_nonce('wp_rest'),
]);
}
function rest() {
// Register route.
register_rest_route('my-plugin/v1', '/uid', [
'methods' => WP_REST_Server::READABLE,
'callback' => [$this, 'rest_callback'],
]);
}
function rest_callback($data) {
// Get current user ID.
$data = [
'uid' => get_current_user_id(),
];
$response = new WP_REST_Response($data, 200);
// Set headers.
$response->set_headers(['Cache-Control' => 'must-revalidate, no-cache, no-store, private']);
return $response;
}
}
new MyPlugin();
The contents of example-script.js are as follows:
(function($) {
$(document).ready(function() {
var settings = MyPluginSettings;
$.ajax({
url: '/wp-json/my-plugin/v1/uid',
method: 'GET',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', settings.nonce);
}
}).done(function(response) {
// Will return your UID.
console.log(response);
});
});
})(jQuery);