title: Wordpress admin/ajax not detecting user logged in
body: <p>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:</p>
  
  <pre><code>&lt;?php
      $user_id = get_current_user_id();
  ?&gt;
  &lt;script&gt;
      alert("Logged in as user #&lt;?php echo $user_id; ?&gt;");
  &lt;/script&gt;
  </code></pre>
  
  <p>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.</p>
  
  <p>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):</p>
  
  <pre><code>$.ajax({
      url: ajaxUrl,
      type: "post",
      data: { 
          action: 'test_ajax'
      },
      beforeSend: function(){},
      complete: function(){},
      success: function(data){
          alert(data);
      },
      error: function(){}
  });
  </code></pre>
  
  <p>And in my functions.php:</p>
  
  <pre><code>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();
  }
  </code></pre>
  
  <p>What I've noticed is that sometimes wp_ajax won't even run, so it will echo 0. So I added nopriv:</p>
  
  <pre><code>add_action('wp_ajax_nopriv_test_ajax', 'test_ajax');
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <hr>
  
  <hr>
  
  <p>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:</p>
  
  <ol>
  <li>Log into Wordpress </li>
  <li>Go to index.php. </li>
  <li>You will get the first alert that says you are logged in, but the second alert (from admin-ajax)
  says otherwise. </li>
  <li>Go to /wp-admin. Since you already logged in, you will see your dashboard without having to log in again. </li>
  <li>Go back to index.php. Both alerts are correct now.</li>
  </ol>