Style Taxonomy Posts? (4 posts)

  1. mcdavis00
    Posted 5 years ago #

    Is there a way to add a Body Class type to posts under a taxonomy category? I'd like to use CSS to style each post within specific groups, but can't seem to find the proper code.

    The below related links seem to get me CLOSE to the solution, either styling posts within a category, or the archive listing of taxonomies. But nothing I've seen explains how to hook on to posts within the taxonomy categories (e.g.; the custom taxonomy is "animals", the group is "dogs", and I'd like to have all posts under the "dogs" group to have a "dogs-single" body class I can style).





  2. vitamincee
    Posted 5 years ago #

    I'm pretty sure this is what you need. I got this working to show both the category & taxonomy class on a single post:

    // add css class to body on single post.
    function add_category_to_single($classes) {
            if (is_single() ) {
                    global $post;
                    foreach((get_the_category($post->ID)) as $category) {
                            $classes[] = 'category-' . $category->category_nicename;
            $terms = wp_get_object_terms($post->ID, 'add-your-taxonomy-here');
            $count = count($terms);
            if ( $count > 0 ){
                    foreach ( $terms as $term ) {
                            $classes[] =  "taxonomy-" . $term->name;
            return $classes;
  3. trixienolix
    Posted 4 years ago #

    I would love it if anyone could help me with this.

    vitamincee I tried your code and this is what I get in the body tag

    <body class="single single-bespoke postid-11 taxonomy- taxonomy-">

    i.e. it says taxonomy-
    but doesn't add the actual taxonomy term in.

    Can you help?

  4. trixienolix
    Posted 4 years ago #

    This worked for me. Remember to change "your_taxonomy_name_here" to your actual taxonomy name.

    // add taxoonomy term to body_class
    function wpprogrammer_custom_taxonomy_in_body_class( $classes ){
      if( is_singular() )
        $custom_terms = get_the_terms(0, 'your_taxonomy_name_here');
        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' );

Topic Closed

This topic has been closed to new replies.

About this Topic