Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress admin/ajax not detecting user logged in

Tags:

ajax

wordpress

I am experiencing an issue in Wordpress where an AJAX call sometimes cannot detect that the user is logged in. At the end of my index.php file of my theme, I have the following code:

<?php
    $user_id = get_current_user_id();
?>
<script>
    alert("Logged in as user #<?php echo $user_id; ?>");
</script>

So if you're a user that is logged in and visits the page, you will get an alert showing your user id. This works great.

However, when I perform an AJAX call through admin-ajax.php, it sometimes will not detect that the user is logged in. Here's what I have later in my index.php that performs the ajax call (using jQuery ajax):

$.ajax({
    url: ajaxUrl,
    type: "post",
    data: { 
        action: 'test_ajax'
    },
    beforeSend: function(){},
    complete: function(){},
    success: function(data){
        alert(data);
    },
    error: function(){}
});

And in my functions.php:

add_action('wp_ajax_test_ajax', 'test_ajax');
function test_ajax() {
    $user_id = get_current_user_id();
    echo "Your user id is: ".$user_id; 

    exit();
}

What I've noticed is that sometimes wp_ajax won't even run, so it will echo 0. So I added nopriv:

add_action('wp_ajax_nopriv_test_ajax', 'test_ajax');

But even when that is run, it'll still think that the user is not logged in, and get_current_user_id() will return 0.

I've also tried wp_get_current_user(); and global $current_user;, but they return empty users as well, i.e. there's no user logged in.



I'm not sure what's happening here, because get_current_user_id() in index.php works, but sometimes admin-ajax doesn't think so (not all the time, sometimes-- and I'm having trouble figuring out why this is so intermittent...). What I have noticed though is this works, and I'm not sure why either:

  1. Log into Wordpress
  2. Go to index.php.
  3. You will get the first alert that says you are logged in, but the second alert (from admin-ajax) says otherwise.
  4. Go to /wp-admin. Since you already logged in, you will see your dashboard without having to log in again.
  5. Go back to index.php. Both alerts are correct now.
like image 703
Chun Avatar asked Mar 21 '26 16:03

Chun


1 Answers

try this and let me know:

<?php
    add_action('wp_ajax_test_ajax', 'test_ajax');
    function test_ajax() {

        global $current_user;

        $user_id = get_current_user_id();
        echo "Your user id is: ".$user_id; 

        exit();

    }
?>
like image 70
Manan Avatar answered Mar 24 '26 23:03

Manan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!