Why isn’t is_page_template() adding a body class?

I want to conditionally add a body class depending on what template is being used.

I can’t figure out why the following code is not working…

function damsonhomes_body_classes( $classes ) {

  if (is_page_template('single.php')) {

    $classes[] = 'sans-hero';

  }

  return $classes;

}

add_filter( 'body_class', 'damsonhomes_body_classes');

Thanks all

2 Answers
2

The is_page_template() function is the incorrect function to use in this case as it checks against Page Templates and single.php is just a normal template, not a page specific one, usually meant for posts.

The function you’re probably looking to use instead is is_single( $optional_posttype ) which will look for singular view of a post type, post by default.

if( is_single() ) {
    /** ... **/
}

You could also check against the basename if you really wanted to:

global $template;
$template_slug = basename( $template );

if( 'single.php' === $template_slug ) {
 /** ... **/
}

Leave a Comment