I am currently building a plugin and it doesn't know when a user is logged in.

global $current_user;
echo $current_user->ID;

It works when embedded on a template but not on a plugin? I have a custom database that depends on user_id, whenever I insert a record, user_id field always has a zero value while others have the correct one.

2 Answers 2


The $current_user global isn't setup until right before the 'init' action is called. So any code using it shouldn't be fired until that action or later.

I would also suggest using the get_current_user_id() method instead of getting the global directly.

  • It diddn't work because it doesn't know whether or not a user is logged in. My plugin hooks a listener into wp_footer when it is page x. Now when I view/load page x in the browser, it knows that a user is logged in, enabling it to know the value of $current_user->ID. But when that page x is called by a service from outside the domain, it doesn't. Is there another way to get user_ID that's suited in my case?
    – Joann
    Commented Nov 29, 2010 at 15:51
  • What do you mean by "a service from outside the domain" Commented Nov 29, 2010 at 16:27
  • Like when page x is sent with $_POST thru methods like cURL.
    – Joann
    Commented Nov 29, 2010 at 16:31
  • ...in that case, the page isn't loaded into the browser so $current_user->ID isn't set.
    – Joann
    Commented Nov 29, 2010 at 17:02
  • If you're sending the request through cURL, you won't have a user_id unless you're passing in the COOKIE through the headers. Commented Nov 29, 2010 at 18:35

Try using is_user_logged_in() to check whether the user is logged in. It will return true or false depending on whether the user is logged in.

  • Yah I already tried it. That's how I determined if $current_user->ID is set or not. In my plugin I placed a code that checks is_user_logged_in() and sends Is login: yes/no string to my email add. When page x is sent with http vars, I get the no in the string. However, if I embed echo is_user_logged_in(); into page x's template and load it into the browser, it says I am logged in. I hope I made myself clear.
    – Joann
    Commented Nov 29, 2010 at 18:30
  • ...which leads me to think that variables/methods/etc that depend on session(not sure) aren't set when the code(hooked somewhere in a page) they are used into is sent/triggered with http post vars.
    – Joann
    Commented Nov 29, 2010 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.