WordPress append page slug to body class

Styling different pages in WordPress is a relatively easy process if you make use of the default body classes that are made available to you, especially the unique page ID class “page-id-123“.

The problem with using the ID class to identify an individual page is that a page ID can quite easily change when working with a development version or even migrating your blog from one install to another.

One solution to this problem is to append the post type and slug as a class name to the body, e.g. ‘page-about‘ or ‘post-hello-world‘.

Simply add the following to your functions.php file to automatically append the classes:

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' );

Note: This method will also apply to individual post pages and custom post types.

7 Replies to “WordPress append page slug to body class”

  1. This is great, one of the better implementations I’ve seen! Word of warning, for some reason whenever add_filter is after the function, it doesn’t always run. I like to put it before the actual function.

    Like

  2. Hey,

    I added this code to my functions.php file but my body classes of each page/post don’t seem to be getting populated with the slug? Can you advise what I might be doing wrong please?

    Many thanks
    Kyle

    Like

  3. It seems that one of the recent WordPress version updates has broken this code’s functionality.

    I’d love to know of an update to the code to fix it.

    Like

  4. function wpprogrammer_post_name_in_body_class( $classes ){
    if( is_singular() )
    {
    global $post;
    array_push( $classes, “{$post->post_type}-{$post->post_name}” );
    }
    return $classes;
    }
    add_filter( ‘body_class’, ‘wpprogrammer_post_name_in_body_class’ );

    Works on WP 3.5.2.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: