Short Body Classes For Page Templates [WordPress]

Styling page templates with CSS is made even easier with the body_class() function which appends all kinds of handy classes to the body element. If you want to make the home page have a unique style, you could do things like:

.home {
   background-image: url(awesomebackgroundimage.jpg);
}

Targeting specific page templates is possible to, but the naming convention is very ugly. The default page template (page.php) would get a body class of page-template-default. A full width template with a filename like full-width-page.php would get a body class of page-template-full-width-php. Basically it adds page-template as a prefix and uss the full file name including the ‘php’ file extension. It’s not just ugly, but it also makes the css file grow if you are using the body class extensively, not to mention making the css harder to read. Oh, and it sucks typing out long class names.

Fortunately, it’s very easy to hook into the body_class function and add your own classes with a shorter naming convention. Here is a snippet that will display a body class of full-width when using full-width.php as the page template.

function my_short_page_template_body_classes( $classes ){
	if( is_page() ){
		$template = get_page_template_slug(); // returns an empty string if it's loading the default template (page.php)
		if( $template === '' ){
			$classes[] = 'default-page';
		} else {
			$classes[] = sanitize_html_class( str_replace( '.php', '', $template ) );
		}
	}
	return $classes;
}
add_filter( 'body_class', 'my_short_page_template_body_classes' );

This function doesn’t replace the longer naming convention WordPress uses by default (so those class names will still be injected too), it just adds a brief class name whenever a page template is being used.

Which would you rather type?

.full-width{
 width: 960px;
}

.page-template-full-width-php {
 width: 960px;
}

Easy choice.

Leave a Reply

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