Identifying posts and pages with an extra “.type-name” body class in WordPress

I wish I could remember where I got this function in order to give credit, because I sure didn’t write it myself.

Add the following code to the theme’s functions.php file and it adds an extra class to the body element that enables me to target pages (and posts, but usually I use it for pages) in my css by name instead of by ID. It makes for MUCH more readable CSS.

// Add page slug to body classes for more readable css
function add_body_class( $classes )
    global $post;
    if ( isset( $post ) ) {
        $classes[] = $post->post_type . '-' . $post->post_name;
    return $classes;
add_filter( 'body_class', 'add_body_class' );

Ordinarily, WordPress provides an ID class in the body so If you need to style something just for one page, it looks something like this:

.page-id-36 {
  background: none;

But if page ID 36 belong to your page on Frogs, now you can just say so right in your CSS:

.page-frogs {
  background: none;

This makes it SO much easier to tell the styles on your Frog page from the styles on your Snakes page when skimming through the CSS.