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.

Read More

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

Related posts

Leave a Reply

2 comments

  1. 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;
    }
    
  2. It’s normal you’ll get errors for pages that are not association with the section.
    Make sure you also return a ‘$classes’ if your ‘if-statement’ fails.

    In other words, make sure you add an else here.

    // 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;
        }
    else 
    {  $classes = 'default-class'; }
    return $classes;
    }
    }
    add_filter('body_class', 'section_id_class');
    

    something like this