在插件中登录用户ID的正确方式是什么?

时间:2012-11-28 作者:PrivateUser

我需要在插件中登录用户id。

这是正确的方式吗?

$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 我们不应该加载wp加载。php文件,因为我们不知道wp加载的位置。找到php文件,它使服务器负载加倍。

所以我真的很困惑。

还有一个问题。。

Check this Rarst\'s Image

根据图像wp负载。php在所有插件之前加载。那么,为什么所有插件作者都再次包含该文件呢?

2 个回复
最合适的回答,由SO网友:EAMann 整理而成

如果您在插件中,WordPress已经加载。您不需要自己加载它。

在任何需要用户ID的函数中,都需要做两件事:

全球化用户数据变量填充用户数据变量以下是一些伪代码:

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

    // Now reference $current_user->ID in your code.
}

SO网友:Chip Bennett

使用is_user_logged_in()wp_get_current_user() (dev docs).

if ( is_user_logged_in() ) {
    // Current user is logged in,
    // so let\'s get current user info
    $current_user = wp_get_current_user();
    // User ID
    $user_id = $current_user->ID;
}

结束