WordPress Plugin: Add Custom Post Type Slugs to Admin <body> Class

If you work with a lot of custom post types in WP, you might eventually find yourself wanting to apply custom CSS to edit.php (the admin page that list all of the posts for a given post type) or post.php (the admin page that let’s you edit the actual post).

Unfortunately, there is no native way to determine this difference between pages and types, so I wrote this:

function add_to_admin_body_class( $classes ) {
	// $classes comes from admin_body_class function
	// get the global post variable
	global $post;
	// instantiate, should be overwritten below
	$mode = '';
	// get the current page's URI (the part /after/ your domain name)
	$uri = $_SERVER["REQUEST_URI"];
	// get the post type from WP
	$post_type = get_post_type($post->ID);
	// set the $mode variable to reflect the editorial /list/ page...
	if ( strstr($uri,'edit.php') ) {
		$mode = 'edit-list-';
	// or the actual editor page
	if ( strstr($uri,'post.php') ) {
		$mode = 'edit-page-';
	// append our new mode/post_type class to any existing classes
	$classes .= $mode . $post_type;
	// and send them back to WP
	return $classes;
// add this filter to the admin_body_class hook
add_filter( 'admin_body_class', 'add_to_admin_body_class' );

So now, when you are viewing a list of your regular posts, you would have a new body class, something like:
And, when editing a post, something like this:

Alternatively, for custom posts, for example “movie”, you would see either:

Thanks to Austin Passy for the initial starting point.

Hope this helps, happy WordPressing,

One Response to WordPress Plugin: Add Custom Post Type Slugs to Admin <body> Class

  1. aarontgrogg says:

    The plugin has been updated in both the WP Repo and on Github.

    Just a slight modification to make sure the plugin only runs in admin pages and on post list pages.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.