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' );

1 Answer
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.

Leave a Reply

Your email address will not be published. Required fields are marked *