How to add Page slug as a body class for static Pages in WordPress

Posted on
5/5 - (226 votes)

A common method to target elements of a particular static Page is by its ID like this: .page-id-2

Wouldn’t it be handy if you could instead use the slug of the Page like this? .page-about

Adding the following in child theme’s functions.php will automatically add a page-slug class to the body element for all static Pages for easier targeting in CSS.

add_filter( 'body_class', 'sk_body_class_for_pages' );
/**
 * Adds a css class to the body element
 *
 * @param  array $classes the current body classes
 * @return array $classes modified classes
 */
function sk_body_class_for_pages( $classes ) {

	if ( is_singular( 'page' ) ) {
		global $post;
		$classes[] = 'page-' . $post->post_name;
	}

	return $classes;

}