HOWTO: Add Page Slug to Body Class in a WordPress Theme

Even though the body_class() function in WordPress outputs a good deal of classes you can easy use – there are sometimes when having the actual page name as a class is helpful (custom CSS).

Usage Example:

  • Page Named: My Test Page
  • You need the ability to apply some CSS to something only on this page

In your functions.php file – add the following:

/* 
 * Add in page nicename to body class
 * @param $classes = array of class names or a string with space-separated classes names
 */
function sdac_body_page_name_class( $classes ) {
	global $post;
		$classes[] = $post->post_name;
	return $classes;
}
add_filter('body_class', 'sdac_body_page_name_class');

Once that function is in place you will then see this on the test page as a class in the body tag: “my-test-page”. With that in place you can then use something like this to make a page specific change in CSS:

.my-test-page .entry {margin:50px 0 100px 0;} 

About the Author...

Jennifer Zelazny

I am a Penn State alumni, avid golfer, kick boxer, volunteer, and Chicagoland WordPress developer who always enjoys a refreshing Coca-Cola.