I currently work on localhost and when I want to test ajax requests to my web server, the function get_current_user_id() always returns 0. When I make the ajax request from my website however, it works. Opening the file in the browser also returns the current wp_user id. The file I make the requests to:
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';
echo get_current_user_id();
I have cors in my .htaccess enabled, other WordPress functions work and I get no warnings or errors in my console.
My .htaccess:
<IfModule mod_rewrite.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with,
content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE,
OPTIONS"
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
ErrorDocument 401 /index.php?status=404
ErrorDocument 403 /index.php?status=404
ErrorDocument 404 /index.php?status=404
ErrorDocument 500 /index.php?status=404
</IfModule>
Thanks for any help in advance!
Edit: Due to the answer from "Tim" I tried the following, but it didn't work.
In my functions.php:
function example_ajax_request()
{
echo get_current_user_id();
die();
}
add_action('wp_ajax_example_ajax_request', 'example_ajax_request');
add_action('wp_ajax_nopriv_example_ajax_request', 'example_ajax_request');
Javascript on localhost:
var ajax = new XMLHttpRequest();
var formData = new FormData();
formData.append("action", "example_ajax_request");
ajax.open(
"POST",
"https://my-website.com/wp-admin/admin-ajax.php"
);
ajax.onload = function() {
console.log(ajax.responseText);
};
ajax.send(formData);
---> returns 0 in console as user is not logged in
Update - Found the solution:
Problem was that javascript didn't send cookies automatically cross-domain. I had to set
var ajax = new XMLHttpRequest();
ajax.withCredentials = true;
After that, I had to add
Header add Access-Control-Allow-Credentials true
to my .htaccess, so cross-domain cookie transfer is allowed.