检查管理员是否已登录WordPress


Check if the administrator has logged into WordPress

我们有一个复杂奇怪的系统,我们需要检查wordpress管理员是否已经登录,这里的登录不仅仅是指会话,而是指发送查询以验证输入凭据的初始秒。我在考虑使用传统的php,我可以这样做:

if(isset($_POST['submit']) { // do something }

但这是不正确的方法。我到底在哪里看到这个作品,我相信它的wp-login.php,但无法找到我正在寻找的东西。

谢谢

try

global $current_user;
$user = get_userdata($current_user->ID);
$userRole = (!empty($user->roles) ? $user->roles : '');
if(in_array('administrator', $userRole)) {
     // do your stuff
}

或者您可以尝试:- http://codex.wordpress.org/Function_Reference/current_user_can

你可以使用非常简洁的Wordpress函数来确定用户的能力,它被称为current_user_can():

<?php if ( current_user_can('update_core') ) { echo 'The current user is Administrator or Super administrator (in Multisite)'; }

只有单站点安装的管理员具有以下功能列表。在多站点中,只有超级管理员具有这些能力:

update_core 
update_plugins 
update_themes 
install_plugins 
install_themes 
delete_themes 
edit_plugins 
edit_themes 
edit_users 
create_users 
delete_users 
unfiltered_html

我们可以在过滤器钩子 login_redirect 中添加一些自定义动作。如果没有提交表单,则$user参数是一个WP_Error对象。

add_filter( 'login_redirect', function( $redirect_to, $requested_redirect_to, $user )
{
    if( !is_wp_error( $user ) && in_array( 'administrator', $user->roles ) )
    {
        # Do your thing; here just inspecting the WP_User Object
        wp_die( 
            sprintf( '<pre>%s</pre>', print_r( $user, true ) ),
            'Var dump',
            array( 
                'response' => 500, 
                'back_link' => true 
            )
        );
    }
    return $redirect_to;
}, 10, 3 );