skip to Main Content

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

2

Answers


  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' );
    
    Login or Signup to reply.
  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' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search