I am working on a WordPress based site, which I am new to. Basically, we are using a plugin to track “points” on the site, and I am using a call to get the user’s wordpress ID for the games. However, the issue is that when I make an ajax call it returns 0 (aka not logged in) for the user ID, but when I visit the PHP page directly it gives me the actual user ID (example: 9). Here is the plugin function that I call in my PHP file:
function cp_currentUser() {
require_once(ABSPATH . WPINC . '/pluggable.php');
global $current_user;
get_currentuserinfo();
return $current_user->ID;
}
and then here is my PHP file
<?php
header("Access-Control-Allow-Origin: *");
require_once("wp-load.php");
echo cp_currentUser();
?>
and here is my cross-domain AJAX call
$.post('http://my.domain.xz/cp_getbalance.php', {}, function(result){
console.log(result);
});
If you go directly to the above URL in your browser while logged in it will give you the user id, but if I attempt it from the AJAX call I just get 0 no matter who I am logged in as.
Your approach is wrong from my point of view.
You cannot get information from a cookie (client-side) on a piece of data that it processes on the server (server-side).
What you need to do is:
Recover the current_user-> ID before the POST call in AJAX
Send the retrieved ID in POST
Process the data via server retrieved via $ _POST variable.
An example.
Your PHP file:
Your cross-domain AJAX call:
Having said that, in WordPress the AJAX calls are done in a completely different way and I suggest you read this guide to better understand: https://codex.wordpress.org/AJAX_in_Plugins
I hope to be proved helpful
Try this:
wp_get_current_user()
You should probably always use
wp_die()
, whether in an Ajax callback or not. Even better, send information back withwp_send_json()
options.The way you work with AJAX in WordPress is a bit wrong.
First of all you should add extend your function:
Function
get_currentuserinfo()
deprecated (Codex).Second your Ajax function: