Search code examples
arrayswordpresstaxonomy

WP Custom Post Type - Display taxonomy as CSS class


I have set up a custom post type in wordpress called "Portfolio". The custom post type then has two taxonomy's set up. They are named 'portfolio_categories' and 'portfolio_sector'.

Currently i am using the following code to gather all my 'portfolio_categories' and store them so they can then be outputted as CSS class to be used for filtering.

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); 
 $termsArray = get_the_terms( $post->ID, "portfolio_categories" );  //Get the terms for this particular item
 $termsString = ""; //initialize the string that will contain the terms
 foreach ( $termsArray as $term ) { // for each term 
 $termsString .= $term->slug.' '; //create a string that has all the slugs 
}
?> 

Then the code to output the terms as classes is as follows:

<div class="<?php echo $termsString; ?>">
Content goes here
</div>

How would i need to edit my code in order to store the taxonomy 'portfolio_sector' and output them as classes also?


Solution

  • You should also get your others terms data, in your context

    <?php
    while ( $the_query->have_posts() ) {
      $the_query->the_post(); 
      $termsArray = get_the_terms( $post->ID, "portfolio_categories" );  //Get the terms for this particular item#
      $termsSectors = get_the_terms( $post->ID, "portfolio_sector" );
      $termsString = ""; //initialize the string that will contain the terms
    
      foreach ( $termsSectors as $term ) { // for each term 
        $termsSector .= $term->slug.' '; //create a string that has all the slugs 
      }
    
      foreach ( $termsArray as $term ) { // for each term 
        $termsString .= $term->slug.' '; //create a string that has all the slugs 
      }
    }
    

    Now you can echo this via the var $termsSector.

    However, as a hint you can also work with get_the_term_list() to get a list include HTML. Maybe this is easier for you and it is not necessary to loop about the array of the terms.