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
.