Working with the WordPress admin_body_class function

WordPress admin_body_class function
For some reason, there are multiple functions in WordPress that do similar things but require different approaches. On the surface, you’d think the admin_body_class function would work the same as the body_class function, but you’d be wrong.
When you modify the body_class function, you hook into the filter like this:

add_filter( 'body_class', 'category_id_class' );
// add category nicenames in body and post class
function category_id_class( $classes ) {
	global $post;
	foreach ( ( get_the_category( $post->ID ) ) as $category ) {
		$classes[] = $category->category_nicename;
	}
	return $classes;
}

If you break that down, you’ll notice that adding a new class name requires extending the $classes array. Straightforward enough, though for some reason when you attempt to work with the admin_body_class function, this approach causes the following error:

Fatal error: [] operator not supported for strings

That’s because it uses a string instead of an array.
As long as your aware of this difference, working with the admin_body_class function is just as straightforward.

add_filter( 'admin_body_class', 'custom_admin_body_class' );
function custom_admin_body_class( $classes ) {
        $classes .= 'custom-class';
	return $classes;
}

I’ve found the above filter useful when I needed to customize the admin after I activated a plugin. With a simple check, the function added a class name to the admin body tag which made it easier for me to use CSS on the page.

Conclusion

The difference is slight but important to understand how to use the admin_body_class function correctly. Then you can easily customize your admin with JavaScript or CSS using that new class name.
You can read a little more about the function in the WordPress codex.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie