'Adding custom body class to the custom archive pages

I have created two custom archive pages: archive-one.php and archive-two.php. Archive pages are placed inside main catalog of my theme. Now what I trying to do is to add a custom body class to each of them like "archive-one" and "archive-two".

I was trying to do this with following code but with no luck:

function archive_class_1( $classes ) {
    if ( is_page_template( 'archive-one.php' ) ) {
        $classes[] = 'archive-one';
    }
    return $classes;
}
add_filter( 'body_class', 'archive_class_1' );


Solution 1:[1]

Confirming this is added to you theme functions.php? Next you can use the same function for both custom archive files (see below examples). Are your custom template files at the root of your theme or a sub folder? if in a sub folder you need to add that path to you check like the examples below. Also confirming that your theme is using the <?php body_class(); ?> function on your themes opening <body> tag (something like <body <?php body_class(); ?>>)?

Custom files at the root of theme

function my_archive_class( $classes ) {
    if ( is_page_template( 'archive-one.php' ) ) {
        $classes[] = 'archive-one';
    }

    if ( is_page_template( 'archive-two.php' ) ) {
        $classes[] = 'archive-two';
    }
    return $classes;
}
add_filter( 'body_class', 'my_archive_class' );

Custom files in sub folder "templates" theme

function my_archive_class( $classes ) {
    if ( is_page_template( 'templates/archive-one.php' ) ) {
        $classes[] = 'archive-one';
    }

    if ( is_page_template( 'archive-two.php' ) ) {
        $classes[] = 'templates/archive-two';
    }
    return $classes;
}
add_filter( 'body_class', 'my_archive_class' );

Solution 2:[2]

add below code it will work properly.

function my_archive_class( $classes ) {
    if ( basename( get_page_template()) == 'archive-one.php') {
        $classes[] = 'archive-one';
    }

    if ( basename( get_page_template()) == 'archive-two.php') {
        $classes[] = 'archive-two';
    }
    return $classes;
}
add_filter( 'body_class', 'my_archive_class' );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mikerojas
Solution 2 Anjan