phpwordpresswordpress-themingcustom-wordpress-pageswordpress-admin

Wordpress how to apply css for specific roles using admin_head hook


I'm looking to add a line of code to apply css to certain roles.

For example:

If role "editor":

#wp-admin-bar-top-secondary{
    display:none;
}  

My snippet code:

add_action('admin_head', 'my_custom_style');

function my_custom_style(){
    echo '<style>
            
        /*remove media button*/
        .wp-media-buttons {
            display: none;
        }
        
        /*remove visual&code tabs*/
        .wp-editor-tabs {
            display: none;
        }
        
          </style>';
}

Solution

  • You could use the roles property of the user object returned from wp_get_current_userDocs function.

    add_action('admin_head', 'my_custom_style');
    
    function my_custom_style()
    {
        $roles = wp_get_current_user()->roles;
    
        if (!in_array('administrator', $roles)) 
        {
            ?>
            <style>
                /*remove media button*/
                .wp-media-buttons {
                    display: none;
                }
    
                /*remove visual&code tabs*/
                .wp-editor-tabs {
                    display: none;
                }
            </style>
        <?php
        };
    }
    

    Note: