WordPress Ajax Call -- WordPress User ID WordPress Ajax Call -- WordPress User ID wordpress wordpress

WordPress Ajax Call -- WordPress User ID


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:

<?phprequire "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


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;


You should probably always use wp_die(), whether in an Ajax callback or not. Even better, send information back with wp_send_json() options.

require_once("wp-load.php");  //Please confirm your wp-load path$current_user = wp_get_current_user();echo $current_user->ID; wp_die(); // this is required to terminate immediately and return a proper response