Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress Ajax Call -- WordPress User ID

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.

like image 238
Katrian Avatar asked Mar 10 '26 04:03

Katrian


1 Answers

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:

header("Access-Control-Allow-Origin: *");

require_once("wp-load.php");

echo $_POST['user_id'];

Your cross-domain AJAX call:

<?php
require "wp-load.php";
global $current_user:
$user_id = $current_user->ID;
?>
var formData = {
    'user_id': '<?php echo $user_id; ?>'
};
//console.log(formData);

$.ajax({
    url: "http://my.domain.xz/cp_getbalance.php",
    type: "post",
    data: formData,
    success: function(result) {
        console.log(result);
    }
});

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

like image 92
Stefano Pascazi Avatar answered Mar 12 '26 18:03

Stefano Pascazi