• Skip to primary navigation
  • Skip to main content
Logos Creative

Logos Creative

Products Made for People, Built in Atlanta

  • Content Library
  • About
  • Contact

Add a Class Conditionally for WordPress Page Templates

Here’s a quick tip for WordPress theme developers that seems to be a bit buried in the Codex.

If you wanted to add a class to the element based on the page template being used, you can’t just go straight for the (usually helpful) is_page_template() function. It can’t be used inside The Loop.

Instead, we see a workaround at the bottom of that article that tells us to use get_page_template_slug().

In my case, I wanted to add a ‘bg-dark’ class to the if mytemplate.php is the page template being used. Here’s how I was able to do it:

function prefix_conditional_body_class($classes) {
	if ( get_page_template_slug(get_the_ID()) === 'mytemplate.php' ) {
		$classes[] = 'bg-dark';
	}
	return $classes;
}

add_filter( 'body_class', 'prefix_conditional_body_class' );

You can run that code in any theme file being called, including functions.php.

May 27, 2014 By Cliff Seal Filed Under: Development, Resources, WordPress

Content Library

Readings on a wide range of topics for small businesses and nonprofits.

 

See Articles

Copyright © 2020 Logos Creative