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

Solutions Collecting From Web of "Why isn't is_page_template() adding a body class?"

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 ) {
 /** ... **/
}

Note that single.php is a template file for a single post, that you would not normally use for pages.

Also note that get_body_class() is already adding some info regarding the current page template:

if ( is_page_template() ) {
    $classes[] = "{$post_type}-template";

    $template_slug  = get_page_template_slug( $post_id );
    $template_parts = explode( '/', $template_slug );

    foreach ( $template_parts as $part ) {
        $classes[] = "{$post_type}-template-" . sanitize_html_class(
          str_replace( array( '.', '/' ), '-', basename( $part, '.php' ) ) );
    }
    $classes[] = "{$post_type}-template-" . sanitize_html_class(
        str_replace( '.', '-', $template_slug ) );
} else {
    $classes[] = "{$post_type}-template-default";
}

If you meant to target single.php then in many cases we don’t need to add a custom body class for that, because get_body_class() already adds the following classes in that case:

if ( is_single() ) {
    $classes[] = 'single';
    if ( isset( $post->post_type ) ) {
        $classes[] = 'single-' . sanitize_html_class( $post->post_type, $post_id );
        $classes[] = 'postid-' . $post_id;

        // Post Format
        if ( post_type_supports( $post->post_type, 'post-formats' ) ) {
            $post_format = get_post_format( $post->ID );

            if ( $post_format && !is_wp_error($post_format) )
                $classes[] = 'single-format-' . sanitize_html_class( $post_format );
            else
                $classes[] = 'single-format-standard';
        }
    }
}

So I would say that in most cases the default body classes are sufficient.