WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Adding taxonomy term to body_class on single.php (4 posts)

  1. trixienolix
    Member
    Posted 1 year ago #

    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:

    <?php
    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.

  2. trixienolix
    Member
    Posted 1 year ago #

    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() ?

  3. trixienolix
    Member
    Posted 1 year ago #

    I found this:
    http://davebonds.com/blog/add-css-classes-for-custom-taxonomies-in-wordpress.html
    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...

  4. trixienolix
    Member
    Posted 1 year ago #

    ok after a few days research ... I found this which works:
    http://wordpress.org/support/topic/style-taxonomy-posts?replies=3#post-2815963

    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

Topic Closed

This topic has been closed to new replies.

About this Topic