How to add a body class based on a custom taxonomy term

I’m trying to insert the slugs of custom taxonomies as classes in the opening body tag on certain WordPress pages. What I have so far is causing errors.

I found a bit of help with the examples here and here, and it works, except that it gives an error on any page that doesn’t have a term from the “section” taxonomy.

The error is:

Warning: join() [function.join]: Invalid arguments passed in /home/*****/public_html/example.com/wp-includes/post-template.php on line 387

and the code is:

// add classes to body based on custom taxonomy ('sections')
// examples: section-about-us, section-start, section-nyc
function section_id_class($classes) {
    global $post;
    $section_terms = get_the_terms($post->ID, 'section');
    if ($section_terms && !is_wp_error($section_terms)) {
        $section_name = array();
        foreach ($section_terms as $term) {
            $classes[] = 'section-' . $term->slug;
        }
    return $classes;
    }
}
add_filter('body_class', 'section_id_class');

2 Answers
2

What is the job of $section_name? Also you must get an return; you if statement kill the default return. It is important, if your if statement fails.

maybe this works, but not tested, write from scratch.

add_filter( 'body_class', 'section_id_class' );
// add classes to body based on custom taxonomy ('sections')
// examples: section-about-us, section-start, section-nyc
function section_id_class( $classes ) {
    global $post;

    $section_terms = get_the_terms( $post->ID, 'section' );
    if ( $section_terms && ! is_wp_error( $section_terms ) ) {
        foreach ($section_terms as $term) {
            $classes[] = 'section-' . $term->slug;
        }
    }

    return $classes;
}

Leave a Comment