Wrap each term in custom span/class

I am trying to print out a list of categories, and wrap each in a <span> with a custom class.

When I try the below (see foreach $terms as $term line) its prints out the categories twice, and each span has both categories in the class.

Read More

How can I run a foreach that only grabs the span of the category its listing?

Current erroneous sample output from current query below is something like this (user analytics, user feedback are separate categories):

<span class="cat user analytics user feedback">user analytics user feedback</span>
<span class="cat user analytics user feedback">user analytics user feedback</span>

PHP

<?php
/* 
Query the post 
*/
$args = array( 'post_type' => 'company', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
  while ( $loop->have_posts() ) : $loop->the_post(); 

/* 
Pull category for each unique post using the ID 
*/
$terms = get_the_terms( $post->ID, 'industry' );  
     if ( $terms && ! is_wp_error( $terms ) ) : 

         $links = array();

         foreach ( $terms as $term ) {
             $links[] = $term->name;
         }

         $tax_links = join( " ", str_replace(' ', ' ', $links));          
         $tax = strtolower($tax_links);
     else : 
   $tax = '';         
     endif; 


        /* Insert category name into portfolio-item class */ 
        echo '<div class="all portfolio-item '. $tax . '">';
        echo '<a href="#" class="company">';
        echo'<div class="thmc">';
        echo '<div class="thumbnail">'; 
        echo the_post_thumbnail();
        echo '</div>';
         echo '</div>';
          echo '</a>';
           echo '<div class="overly">';
        echo '<h4 class="company-title">'; 
        echo the_title();
        echo '</h4>';

       foreach($terms as $term){ 
        echo '<span class="cat ' . $tax . '">';
        echo $tax;
        echo '</span>';

        }

        echo '<div class="company-desc">';
        echo the_content();
        echo '</div>';
        echo '<div class="drop-menu-arrow"></div>';
        echo '</div>'; 


        echo '</div>'; 

  endwhile; ?>

Related posts

1 comment

  1. Simplified version for demonstration:

    $terms = get_the_terms( $post->ID, 'industry' );  
    
    foreach( $terms AS $term) {
        $class = $term->slug;
        echo '<span class="cat ' . $class . '">';
        echo $term->name;
        echo '</span>';
    }
    

    You would of course want to implement some checks like you have in the code in your question.

Comments are closed.