Chun
Chun

Reputation: 1988

Wordpress admin/ajax not detecting user logged in

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.

Upvotes: 3

Views: 2711

Answers (2)

Fanky
Fanky

Reputation: 1785

Try to reset ajaxurl manually before using it, for example:

var ajaxurl="http://" + document.domain + "/wp-admin/admin-ajax.php";

My problem was that when accessing from en.mysite.com , the ajaxurl was called as www.mysite.com, which somehow made them not communicate.

Upvotes: 0

Manan
Manan

Reputation: 1195

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();

    }
?>

Upvotes: 2

Related Questions