Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I need to get logged in user id inside my plugin.

Is this the proper way?

$root = dirname(dirname(dirname(dirname(__FILE__))));
if (file_exists($root.'/wp-load.php')) {
require_once($root.'/wp-load.php');
} 
$user_id = get_current_user_id();

Otto saying that we shouldn't load wp-load.php file since we have no idea where wp-load.php file located and it doubles the server load.

So I'm really confused.

And one more question..

Check this Rarst's Image

According to that image wp-load.php loaded before all the plugins. So why all plugin authors include that file again?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

If you're inside a plugin, WordPress is already loaded. You don't need to load it yourself.

Inside whatever function needs the user ID, you need to do two things:

  1. Globalize the user data variable
  2. Populate the user data variable

Here's some pseudocode:

function some_function_that_needs_user_info() {
    global $current_user;
    get_currentuserinfo();

    // Now reference $current_user->ID in your code.
}
share|improve this answer
    
Ahh.. Got it. Thanks.. –  Giri Nov 28 '12 at 17:21
add comment

Use is_user_logged_in() and get_currentuserinfo().

if ( is_user_logged_in() ) {
    // Current user is logged in,
    // so let's get current user info
    global $current_user;
    get_currentuserinfo();
    // User ID
    $user_id = $current_user->ID;
}
share|improve this answer
    
Thanks. So this plugin coded in the wrong way right? (line 12 - 17) –  Giri Nov 28 '12 at 17:27
    
That's really a separate question. Without digging more into that Plugin, I can't really comment on why it's loading wp-load.php. I do know, however, that it is not necessary for getting current user info. –  Chip Bennett Nov 28 '12 at 17:29
    
ok thanks. .... –  Giri Nov 28 '12 at 17:31
    
It's actually necessary for that purpose, due to the fact that it's loading the majority of the WordPress core. My assumption is that this is a part of the plugin that is called outside of the scope of WordPress - such as a remote AJAX call to the file or anything related to that, where you have no access to the WordPress functions such as get_currentuserinfo. However, it's not really a good practice to include the core this way. –  Mario Peshev Nov 28 '12 at 17:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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