Getting WordPress User ID in Ajax Request

Hey everyone, I’m having trouble with a WordPress site I’m building. I’m using a plugin to track points, and I need to get the user’s WordPress ID for some games. The problem is that when I make an Ajax call, it always returns 0 (meaning not logged in). But if I visit the PHP page directly, it shows the correct user ID.

Here’s a simplified version of what I’m doing:

// In my PHP file
function get_current_wp_user() {
    require_once('wp-includes/user.php');
    $user = wp_get_current_user();
    return $user->ID;
}

echo get_current_wp_user();

And here’s my JavaScript:

$.ajax({
    url: 'http://mysite.com/get_user_id.php',
    method: 'POST',
    success: function(response) {
        console.log('User ID:', response);
    }
});

When I load the PHP file directly in the browser, it shows the correct ID. But the Ajax call always returns 0. Any ideas what I’m doing wrong? Thanks!

I’ve run into this issue before, and it can be a real head-scratcher! The problem is likely related to how WordPress handles authentication for Ajax requests. When you make an Ajax call, it doesn’t carry over the user’s session by default.

Instead of calling your PHP file directly, use WordPress’s built-in Ajax handler. Set up a proper Ajax action in your theme or plugin, and use wp_localize_script to pass the Ajax URL to your JavaScript.

Here’s a quick example:

In your PHP:

add_action('wp_ajax_get_user_id', 'my_get_user_id');
function my_get_user_id() {
    echo get_current_user_id();
    wp_die();
}

In your JavaScript:

jQuery.post(ajaxurl, { action: 'get_user_id' }, function(response) {
    console.log('User ID:', response);
});

This approach ensures that WordPress handles the authentication properly for your Ajax requests. Give it a try and let me know if it helps!

I’ve encountered this issue before. The problem likely stems from WordPress not recognizing the Ajax request as authenticated. Instead of creating a separate PHP file, I’d recommend using WordPress’s built-in Ajax functionality.

Try this approach:

In your plugin or theme’s PHP file:

add_action('wp_ajax_get_user_id', 'my_get_user_id_function');
function my_get_user_id_function() {
    echo get_current_user_id();
    wp_die();
}

In your JavaScript file:

jQuery.post(ajaxurl, { action: 'get_user_id' }, function(response) {
    console.log('User ID:', response);
});

Remember to enqueue your script and localize the ajaxurl variable. This method ensures WordPress handles authentication properly for Ajax requests. Let me know if you need more clarification.

hey mate, i think i know whats going on. wordpress needs to know its an ajax request from the same site. try adding this to ur php file:

define(‘DOING_AJAX’, true);
if (!defined(‘ABSPATH’)) {
require_once(‘…/…/…/wp-load.php’);
}

that should do the trick. lmk if it works!