L-Dawg
L-Dawg

Reputation: 1

How do I add CSS only for certain user roles?

On all posts, I'm trying to hide the Update button, which is contained within this box:

<div id="postbox-container-1" class="postbox-container">

I only want to hide this box and button for a certain user role, 'Bookings Viewer', which I have created. Here is my code so far:

//Hides the update button for the Booking Viewer user role
add_action( 'wp', 'hide_update_booking_viewer' );
function hide_update_booking_viewer()
{
    $user = wp_get_current_user();
    if ( in_array( 'Bookings Viewer', (array) $user->roles ) ) { ?> 
    <style type="text/css" media="screen">
#postbox-container-1 {display:none;}
</style><?
}

}

Currently the code, which I've placed into functions.php, seems to have no effect. What am I doing wrong?

Upvotes: 0

Views: 1704

Answers (2)

L-Dawg
L-Dawg

Reputation: 1

I've managed to work out the answer for myself - I was adding the action to the wrong hook. wp_head is for the 'front-end' website, so we need to use 'admin_head'. I also echoed out the CSS. Finally, '#publishing-action' refers to the Update button, which is what I was trying to hide specifically.

//Hides the update button for the Booking Viewer user role
function hide_update_booking_viewer()
{
    $user = wp_get_current_user();
    if ( in_array( 'bookings_viewer', (array) $user->roles ) ) { 
    echo('<style type="text/css" media="screen">
#publishing-action {display:none; !important}
</style>');
}

}
add_action( 'admin_head', 'hide_update_booking_viewer' );

Upvotes: 0

Andrey
Andrey

Reputation: 702

Try with a different hook:

function hide_update_booking_viewer() {
$user = wp_get_current_user();
if ( in_array( 'Bookings Viewer', (array) $user->roles ) ) {
'<style>
#postbox-container-1 {display:none !important;}
</style>'
} }

add_action( 'wp_head', 'hide_update_booking_viewer' );

This should output the styles into the head section of your webpage for the user "Bookings Viewer" if you registered the user role correctly.

But, as suggested in this post, it is better to rely on capabilities of the user rather than on it's name. Example:

function hide_update_booking_viewer_1() {
if ( current_user_can( 'read' ) ) {
'<style>
#postbox-container-1 {display:none !important;}
</style>'
} }

add_action( 'wp_head', 'hide_update_booking_viewer_1' );

A list of capabilities and role types can be found here.

Upvotes: 1

Related Questions