Support » Fixing WordPress » Adding taxonomy term to body_class on single.php

  • Resolved trixienolix


    How can I add the name of the custom taxonomy term that a post belongs to on single.php into the body_class?

    I’ve been able to add it when on taxonomy.php but when I click through from this page to a single post, the taxonomy term class disappears from the body tag.

    I’ve checked that when on single.php the taxonomy term is recognised by adding this code in:

    if( false != get_the_term_list( $post->ID, 'bespoke_type' ) ) {
         echo 'The taxonomy is:' . get_the_term_list($post->ID,'bespoke_type', ' ', ' ', '' );

    and this does indeed return the name of my taxonomy term (with a link to its taxonomy.php).

    Any help would be marvelous.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Having more of a rummage, it seems that get_the_terms is a better function to use.

    How do I code it so that I can add the output of get_the_terms to my body_class() ?

    I found this:
    the last example is really close. If i change it slightly from post_class to body_class though i get errors.

    My code:

    add_filter( 'body_class', 'mysite_body_class', 10, 3 );
    if( !function_exists( 'mysite_body_class' ) ) {
        function mysite_body_class( $classes, $class, $ID ) {
            $taxonomy = 'name_of_your_taxonomy_here';
            $terms = get_the_terms( (int) $ID, $taxonomy );
            if( !empty( $terms ) ) {
                foreach( (array) $terms as $order => $term ) {
                    if( !in_array( $term->slug, $classes ) ) {
                        $classes[] = $term->slug;
            return $classes;

    The errors i get:

    Warning: Missing argument 3 for mysite_body_class()

    Anyone?? I’m so close…

    ok after a few days research … I found this which works:

    and also this (NB: change the taxonomy name to your one)

    // another go
    function wpprogrammer_custom_taxonomy_in_body_class( $classes ){
      if( is_singular() )
        $custom_terms = get_the_terms(0, 'your-taxonomy-name');
        if ($custom_terms) {
          foreach ($custom_terms as $custom_term) {
            $classes[] = 'custom_tax_' . $custom_term->slug;
      return $classes;
    add_filter( 'body_class', 'wpprogrammer_custom_taxonomy_in_body_class' );

    Hope this is useful for someone

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Adding taxonomy term to body_class on single.php’ is closed to new replies.