0

I am trying to add a list of terms as a class for custom post types.

<?php while($portfolio->have_posts()) : $portfolio->the_post(); ?>

                    <?php $categories = get_the_terms($post->ID, 'project_type');
                        foreach($categories as $category){

                            return $category->name;
                        }
                    ?> 


                    <div class='portfolio-tile <?php echo $category ;?>'>
                        <?php the_post_thumbnail('medium' ); ?>

                    </div>

                <?php endwhile; ?>

                </div>

        <?php wp_reset_query(); ?>

2 Answers 2

2

If you use return then your loop will not work properly. You can try the code this way:

<?php while($portfolio->have_posts()) : $portfolio->the_post(); ?>

                    <?php $term_class = ''; 
                        $categories = get_the_terms($post->ID, 'project_type');
                        foreach($categories as $category){

                            $term_class .= ' ' . $category->name;
                        }
                    ?> 


                    <div class='portfolio-tile <?php echo trim($term_class) ;?>'>
                        <?php the_post_thumbnail('medium' ); ?>

                    </div>

                <?php endwhile; ?>

                </div>

        <?php wp_reset_query(); ?>
4
  • I'm getting a all the terms form the terms list and the increment by 1 with each div.
    – Justin
    Sep 5, 2014 at 15:40
  • I did not understand your question. Can you explain more? Sep 5, 2014 at 15:45
  • Each custom post type will have 2-3 terms associated with it. I need to get those terms added to each posts class. Thanks for you help.
    – Justin
    Sep 5, 2014 at 15:55
  • foreach for terms is not working properly? i think that it is adding multiple terms and loop is working perfectly Sep 5, 2014 at 16:02
0

I found that the best way to handle this problem was to leverage the post_class function and add the loop through the function.php file. this is the code in the function.php file:

function term_class($classes){

global $post;

$taxonomies = array('project_type');
$terms = get_the_terms( $post->ID , $taxonomies);

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

 return $classes;

}

add_filter( 'post_class', 'term_class' );
add_filter( 'body_class', 'term_class' );

Then I just added the post_class() function the custom posts template. Thanks for all the help everyone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.