WP 管理栏隐藏在前端?

WP Admin bar hidden on front-end?

我正在使用以下代码为特定用户隐藏 WP 管理栏的功能:

//Hide admin bar for subscribers
if (current_user_can('subscriber') || !is_user_logged_in() ) {
    // user can't view admin bar
    show_admin_bar(false);
}
else {
    show_admin_bar(true);
}

它适用于 subscribersvisitors,但当以 administrator 身份登录时,管理栏不会显示在前端。谁能告诉我我做错了什么?

解决方案:上面的代码有效

试试,

//Hide admin bar for subscribers
if( current_user_can('subscriber') || current_user_can('visitor') ) {
  // user can't view admin bar
  show_admin_bar(false);
} else {
  show_admin_bar(true);
}

更新代码:

//Hide admin bar for all users except administrators
if( current_user_can('manage_options') ) {
  show_admin_bar(true);
} else {
  // All other users can't view admin bar
  show_admin_bar(false);
}

检查您的用户设置中是否选中了查看网站时显示工具栏

使用 show_admin_bar 过滤器 hide/display 管理栏。

/**
 * Checks if the user belongs to the roles.
 * 
 * @param int/WP_User $user Either user_id or WP_User object.
 * @param string/string[] $roles Single roles or array of roles.
 */
function is_user_in_role($user, $roles ) {
    // Set user_id to null;
    $user_obj = null;

    // Check if the $user is integer.
    if ( is_int( $user ) ) {
        $user_obj = get_user_by( 'id', $user );
    }

    // Check if the $user is object.
    if ( $user instanceof WP_User) {
        $user_obj = $user;
    }

    // Bail if the $user_id is not set.
    if ( null === $user_obj) {
        return false;
    }

    // Check if the user belons to the role.
    if ( is_string( $roles ) ) {
        return in_array( $roles, (array) $user_obj->roles );
    }

    // Check if the user belongs to the roles.
    if ( is_array( $roles ) ) {
        $user_belong_to = true;
        foreach( $roles as $role ) {
            if ( ! in_array( $role, (array) $user_obj->roles ) ) {
                $user_belong_to = false;
            }
        }
        return $user_belong_to;
    }

    // Return false if nothing works.
    return false;
}

add_filter( 'show_admin_bar', 'hide_admin_bar' );
function hide_admin_bar() {
    $user = wp_get_current_user();
    if ( is_user_in_role($user, 'administrator' ) ) {
        return false;
    } else {
        return true;
    }
}

参考: https://cpothemes.com/disable-wordpress-admin-bar