Adding Post Type and Slug to the Body Classes

When I first started working with WordPress, in order to style things on a particular page, I often would use the page or post’s ID to target the styles for that page. After all, out-of-the-box, WordPress gives you a class on the body tag containing the post type and the ID like postid-455 or page-id-525.

The problem I had with this was trying to keep the IDs between my local development site and the live site in sync. Usually the client will be adding and changing items on the live site while you will be doing the same on the local development site. Unless you are always pulling down the latest changes made to the live site, and pushing up changes made to your local database, your IDs are going to be different for the same page on the two sites.

The way I have gotten around this lately is to add the post type and the post or page slug to the body class. That way, by using the same slug locally and on the live site, I can be sure to have a unique class on the body tag in which to target for post-specific styles. The code for this is pretty easy using WordPress’s body_class filter. In the functions.php file of my theme, I can add:

// Add slug to body class
function scc_add_slug_to_body_class( $classes ) {
    global $post;
    if ( isset( $post ) ) {
        $classes[] = $post->post_type . '-' . $post->post_name;
    }
    return $classes;
}
add_filter( 'body_class', 'scc_add_slug_to_body_class' );

Then, if I were on a page that had the slug who-we-are, I would have a class on the body tag, page-who-we-are, ready for use.

Leave a Reply

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