Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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:

  • Some users could possibly have more than one role, that’s why I used in_array function!
  • Of course you could do the opposite by using the exclamation mark/’not operator’. (i.e !in_array())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading