Add The Category and Page Title to Pages As Body Classes

Posted on 21st September, 2015 Leave a Comment

To add some custom styles to individual category pages you can use this snippet to add a body class to our posts.

functions.php

/* 
 * ADD CATEGORY AND PAGE TITLE TO PAGES AS CLASSES
 *************************************************************/
 
function add_slug_body_class( $classes ) {
	
	// Grab the page title
	global $post;
	if ( isset( $post ) ) {
		$classes[] = $post->post_type . '-' . $post->post_name;
	}
	
	// Grab the category
	if ( is_single() && !is_front_page() && !is_home() )
		return $classes;
	$post_categories = get_the_category();
	foreach( $post_categories as $current_category ) {
		$classes[] =  $current_category->slug; 
	}
	return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]