如何确定管理员是否在循环之外登录

时间:2011-10-20 作者:markratledge

我需要能够知道是否有管理员登录到了循环外部。

对于一些属于WP站点但不使用require( \'../wp-load.php );

我需要做的是阻止Google Analytics tracker JS为登录的管理员开火,但要跟踪其他人。

如何确定管理员是否在循环之外登录?检查WP登录的cookie?或者我必须使用wp-load.php?

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

您可以使用current\\u user\\u can()确定是否记录了管理员用户,并使用wp\\u enqueue\\u脚本和函数中的if语句加载您的Google跟踪代码。php

if ( ! current_user_can( \'edit_posts\' ) ) {
        wp_enqueue_script( \'google-tracking\');
    } 

SO网友:EarnestoDev

要么使用wp-load.php (性能征税)或执行以下操作:

// Capture \'init\' event in a plugin placed in /wp-content/mu-plugins/
// This will keep the shared cookie fresh for each load.
add_action(\'init\', function(){
    $cookie_server = $_SERVER[\'SERVER_NAME\'];
    // To work an all subdomains uncomment:
    // $cookie_server = strchr($_SERVER[\'SERVER_NAME\'], \'.\');
    // Now check if current user is an Admin and do this: Signal Admin presence by
    // setting up a special value cookie that you can detect in your other script.
    // Prepare a salt and a hash here caculated from $salt, User-Agent and Remote IP
    $special_salt = \'setup a string here others will not know\';
    $special_hash = md5($_SERVER[\'HTTP_USER_AGENT\'].$_SERVER[\'REMOTE_ADDR\'].$special_salt);
    if(!current_user_can(\'activate_plugins\')){
        // If the user is not an admin remove the special cookie (if exists)
        setcookie(\'crosscript_auth\', null, time() - 24 * 3600, \'/\', $cookie_server, is_ssl(), true);
    }else{
        // If the user is an admin add the special cookie with the $special_hash value
        setcookie(\'crosscript_auth\', $special_hash, strtotime(\'+1 week\'), \'/\', $cookie_server, is_ssl(), true);
    }
    // Now, in your other script, use the $special_salt and $special_hash from here
    // to compare to the $_COOKIE[\'crosscript_auth\'], if available.
    // That will tell you if an Admin is logged in
}); // PHP 5.3 Closure, just change to named function for 5.2
只需阅读代码中的注释。我试图描述它背后的全部逻辑。它非常安全,并且特殊的Cookie绑定到IP/用户代理。有了适当的盐,你应该不会有问题,除非1337黑客以你为目标:)这也是你调整的开始。

当做

PS: <如需任何其他澄清,请随时询问

结束

相关推荐

在wp-admin中操作主题列表

我正在运行一个多站点网络,安装并激活了100多个主题。有没有办法操纵wp admin中可用主题的列表,以便某些主题首先出现在列表中?(一种“特色”或“推荐”)在前9个字母之后,或者按照默认字母顺序排列,就可以了。显然,在谷歌上搜索“wordpress”和“themes”这两个词在这种情况下是毫无结果的。