WordPress Ajax Call — WordPress User ID

2019-09-10 21:24发布

问题:

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.

回答1:

Try this: wp_get_current_user()

require_once("wp-load.php");  //Please confirm your wp-load path
$current_user = wp_get_current_user();
echo $current_user->ID;
exit;