Blog: WordPress
Paintbrushes

Using WordPress Custom Admin Styles

Avatar for John Locke

John Locke is a SEO consultant from Sacramento, CA. He helps manufacturing businesses rank higher through his web agency, Lockedown Design & SEO.

Sometimes, it is advantageous to add custom CSS to the WordPress admin area.

Perhaps you want to show an admin area that does not resemble the default WordPress back end.

In other cases, you may want to serve specific admin styles, based on the user role of who’s logged in.

Here’s how you add WordPress custom admin styles for logged in users, and as a bonus, how to add the current user role to the body tag of the admin area, so you can target it in CSS.

Adding Custom Styles To The WP Admin Area

By adding a custom function and action to our functions.php file, we can output inline CSS in the head of admin area pages.



add_action('admin_head', 'ld_custom_admin');

function ld_custom_admin() {
  echo '<style>
    // WP Admin Styles go here
  </style>';
}


This function echoes out inline styles for anyone who is logged into the admin area of your WordPress site.

Because admin_head is an action event, we can hook into it with our custom function, which executes at that point.

But what if you wanted to serve up specific styles based on the user role of the logged in user?

There’s a way to do that, too. (This one also goes in your functions.php file.)



/**
 * Add role to admin body class
 * 
 */

function add_role_to_admin_body($classes) {
	
	global $current_user;
	$user_role = array_shift($current_user->roles);
	
	$classes .= 'role-'. $user_role;
	return $classes;
}
add_filter('admin_body_class', 'add_role_to_admin_body');

So, what’s going on in this function?

First, we’re finding the current logged in user. Then we’re going through the array of information about that user, and locating their user role, and storing that in a variable.

Then, we’re grabbing the $classes variable, which stores the CSS classes for the body element for that page, and adding the class role-[the_user_role_here] to that list.

Then we return the $classes variable to the normal flow, and add our function as a filter when the page is loaded.

The end result is each logged in user role will be a CSS class on the WordPress admin pages. This means we can target specific user roles in the custom inline styles we showed you how to do in the first code sample.

Now, whether you choose to develop a custom admin area for everyone, or just specific users, the only limits are your imagination.

Tip: If you want to add custom user roles, you can use a plugin like User Role Editor to accomplish this task.

Avatar for John Locke

John Locke is a SEO consultant from Sacramento, CA. He helps manufacturing businesses rank higher through his web agency, Lockedown Design & SEO.

Join the Conversation

Your email address will be kept private. Required fields marked *.