简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM