Home > front end >  Wordpress how to apply css for specific roles using admin_head hook
Wordpress how to apply css for specific roles using admin_head hook

Time:02-02

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

CodePudding user response:

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())
  •  Tags:  
  • Related