简体   繁体   中英

Add custom class to <body> based on assigned tag

Wordpress cms. I have a custom taxonomy - 'csgroup' and it's term - 'expertise-page'. I need to add custom class 'new-class' to <body> when I assign term 'expertise-page' to the page. Here is function in the function.php file but this don't work:

function custom_body_classes( $classes ){
    if ( is_tag('csgroup', 'expertise-page') ) {
        $classes[] = 'new-class';
    }
    return $classes;
}
add_filter( 'body_class', 'custom_body_classes' );

The is_tag(); function will only run on tag archive pages and not on every page, post or custom post type; which I guess you are looking for.

To check if any term (eg expertise-page) from a taxonomy (eg csgroup) is assigned to the current post, page or custom post type; you will have to use the has_term() function from WordPress.

This function confirms if the current page, post or custom post type has your desired taxonomy term attached with it.

You can learn more about this function and many more on WordPress Developer Documentations. Here's the link for it; has_term()

Hope this explains and solves your problem.

function custom_body_classes( $classes ){
    if ( has_term('expertise-page', 'csgroup') ) {
        $classes[] = 'new-class';
    }
    return $classes;
}
add_filter( 'body_class', 'custom_body_classes' );

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