admin管理员组

文章数量:1122832

How can you Hide a specific Page or Page ID or set of CSS IDs for user Roles that are not admins? Specifically User Role (Subscriber)

I've tried

    global $post;
$post_id = $post->ID;
if( $post_id = 42 && current_user_can( 'read' ) {
    // do stuff
}

With no Return results.

How can you Hide a specific Page or Page ID or set of CSS IDs for user Roles that are not admins? Specifically User Role (Subscriber)

I've tried

    global $post;
$post_id = $post->ID;
if( $post_id = 42 && current_user_can( 'read' ) {
    // do stuff
}

With no Return results.

Share Improve this question edited Oct 1, 2024 at 15:29 Jeremy Thomas asked Oct 1, 2024 at 15:29 Jeremy ThomasJeremy Thomas 32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can use the body_class filter and the wp_get_current_user() function to add the current user's role to the <body> element, and then hide your elements with that (untested):

add_filter( 'body_class', static function ( $classes ) {
    $user  = wp_get_current_user();
    $roles = $user->roles;

    if ( ! is_array( $roles ) ) {
        $roles = array( 'subscriber' );
    }

    foreach ( $roles as $role ) {
        $classes[] = sprintf( 'role-%s', $role );
    }

    return $classes;
} );
body.role-subscriber #element-id,
body:not( .role-administrator ) .admins-only {
    display: none;
}

Please note that hiding sensitive information using CSS is not effective, as the information will be available in the page's source code: it is much more secure to use PHP to check the user's role and include the sensitive information only in that case.

本文标签: phpHide ID for WordPress User Role Subscriber