Search code examples
phpwordpresstaxonomy

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

Solution

  • 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 (e.g. expertise-page) from a taxonomy (e.g. 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' );