Working with templates in WordPress is something that’s not uncommon. Everything is a template of sorts – from the main page template, single page template, 404 template – all the way to custom templates.

Sometimes, though, you may want to apply a class to the body element based on the template that’s being used so that you can style this particular template a bit differently than the rest of the site.

Body Class Based on a Template

Though you can do it in a number of different ways, to do it we all have our methods so I thought I’d share mine.

Body Class Based on a Template

Before jumping into the code for adding a body class based on a template it’s important to note that I’m assuming that the template is named in the following format: template-{name-of-template}.php.

So let’s say you’re working on a template for displaying information about the weight you’ve lost in a month and you want to do so using a template for this. The template may be named template-weight-loss.php.

Here’s the the the thing: Applying the class name to a single page that uses this template isn’t a big deal. But if you have multiple pages that use this template (which, if you run a site in which numerous people may be using this template, it makes sense, right?) then you’re going to want to make sure you apply the class name to each page that as this template.

But how?

There are a number of ways in which you can do this but it requires at least the following:

  1. Hooking into the body_class hook WordPress provides,
  2. Reading the name of the template,
  3. Applying it to the class name of the body (if the page is using the template)

Luckily, it’s easy to do because the hook passes an array of classes into a hooked function and a given post’s metadata includes whether or not it’s using a template.

With that said, here’s how this can be achieved:

Note that you can use a closure for this rather than a function name hooked and an independent function, but given that different people reading this use different versions of PHP, the easiest way to demonstrate this is to use it above.

Why Do This?

Generally speaking, if your page has the same name as the template that’s being applied then it’s going to have a class name that matches the name of the page.

That is, let’s say you have one page and its name is Weight Loss. The body element will have a weight loss class. But if you use a second, third, fourth, or so on a page that has a different title, it won’t have that class.

If you want to ensure the body has the class name based on the template, then the code above will ensure that this works.