How to assign a class to a page with a custom template?

All we need is an easy explanation of the problem, so here it is.

I tried with the bellow code to assign a body class to a page with a custom template, but this didn’t work. What is wrong here?

function prefix_conditional_body_class($classes) {
    if ( get_page_template_slug(get_the_ID()) === 'mytemplate.php' ) {
        $classes[] = 'mytemplate';
    }
    return $classes;
}

add_filter( 'body_class', 'prefix_conditional_body_class' );

UPDATE 2

The template is assigned to the page with this code:

function my_template_redirect() {
    if ( is_page('search-results') ) : // the page real name
        include (STYLESHEETPATH . '/search-results.php'); // the template real name
        exit;
    endif;
}
add_action( 'template_redirect', 'my_template_redirect' );

UPDATE 1

I modified a little the above function and now it works (replaced get_page_template_slug(get_the_ID()) === "mytemplate.php" with is_page( 8 ), where 8 is the ID of the page):

function prefix_conditional_body_class($classes) {
    if ( is_page( 8 ) ) { // the ID of the needed page
        $classes[] = 'mytemplate';
    }
    return $classes;
}

add_filter( 'body_class', 'prefix_conditional_body_class' );

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Using is_page(8) will make your code a bit static. Let’s make it dynamic as you’re after with is_page_template():

<?php
function prefix_conditional_body_class( $classes ) {
    if( is_page_template('mytemplate.php') )
        $classes[] = 'mytemplate';

    return $classes;
}
add_filter( 'body_class', 'prefix_conditional_body_class' );

Worked for me in a child theme with the template file in the root of the child theme, using template twentyfifteen.

And I don’t know why you need another class to be added, if you are using body_class() you will already get two classes there: page-template-mytemplate and page-template-mytemplate-php. They will be unique and you can use them.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply