Add post/page name + page parent name to body class

WordPress Tips & Tricks
by
Michelle McGinnis
 | 

This will add a page-slug class and a page-parent-slug class to your body tag, along with all the other defaults. Put this in your functions.php file:

function wpprogrammer_post_name_in_body_class( $classes ){
if( is_singular() ) {
     global $post;
     $parent = get_page($post->post_parent);
     array_push( $classes, "{$post->post_type}-{$post->post_name}" );
     array_push( $classes, "{$post->post_type}-parent-{$parent->post_name}" );
     }
return $classes;
}
add_filter( 'body_class', 'wpprogrammer_post_name_in_body_class' );

Also make sure your open body tag looks like this (you can probably find it in header.php):


<body <?php body_class(); ?>>

Many thanks to Utkarsh Kuketri for the original function!

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>