如何仅为某些用户角色添加CSS?

时间:2020-01-14 16:45:09

标签: php css wordpress

在所有帖子上,我都试图隐藏此框中包含的“更新”按钮:

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

我只想为我创建的特定用户角色“ Bookings Viewer”隐藏此框和按钮。到目前为止,这是我的代码:

//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><?
}

}

目前,我放置在functions.php中的代码似乎无效。我在做什么错了?

2 个答案:

答案 0 :(得分:1)

尝试使用其他钩子:

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' );

如果您正确注册了用户角色,这应该为用户“ Bookings Viewer”将样式输出到网页的head部分中。

但是,正如this帖子中所建议的那样,最好依靠用户的功能而不是名字。 示例:

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' );

可以找到功能和角色类型的列表here

答案 1 :(得分:0)

我设法为自己找到了答案-我将操作添加到了错误的钩子上。 wp_head用于“前端”网站,因此我们需要使用“ admin_head”。我也回应了CSS。最后,“#publishing-action”指的是“更新”按钮,这是我专门试图隐藏的按钮。

//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' );
相关问题