Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created June 7, 2018 13:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/e053ff5fdc82af9854bf7031d57a759d to your computer and use it in GitHub Desktop.
Save tommcfarlin/e053ff5fdc82af9854bf7031d57a759d to your computer and use it in GitHub Desktop.
[WordPress] Adding a Body Class Based on a Template
<?php
add_filter('body_class', 'acme_add_body_class');
/**
* If the current page has a template, apply it's name to the list of classes. This is
* necessary if there are multiple pages with the same template and you want to apply the
* name of the template to the class of the body.
*
* @param array $classes The current array of attributes to be applied to the
*/
function acme_add_body_class($classes)
{
if (!empty(get_post_meta(get_the_ID(), '_wp_page_template', true))) {
// Remove the `template-` prefix and get the name of the template without the file extension.
$templateName = basename(get_page_template_slug(get_the_ID()));
$templateName = str_ireplace('template-', '', basename(get_page_template_slug(get_the_ID()), '.php'));
$classes[] = $templateName;
}
return array_filter($classes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment