0

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.

1 Answer 1

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.

1
  • This would have been a great solution. Commented Oct 1 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.