Reputation: 3209
I'm using a Javascript filter which shows and hide a list (loop) of Custom Post Types based on their category.
I'm trying to add the category slug as a class. But I only want to display the categories that are assigned to a specific loop item. Each item can have multiple categories.
I've done it this way, but it dumps all the categories on each loop, not ones specifically for that loop item.
<?php
$pageID = get_the_ID();
$loop = new WP_Query(array('post_type' => 'casestudies', 'posts_per_page' => -1));
$taxonomy = 'custom_casestudies';
$terms = get_terms($taxonomy);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="block-wrap mix <?php foreach ($terms as $term) echo ' ' . $term->slug; ?>">
// loop content
</div>
<?php endwhile; wp_reset_postdata(); ?>
Upvotes: 3
Views: 292
Reputation: 3209
In case this helps anyone else and thanks to Matt (who answered) this is working.
<?php
global $post;
$loop = new WP_Query(array('post_type' => 'casestudies', 'posts_per_page' => -1));
while ($loop->have_posts()) : $loop->the_post();
$terms = wp_get_post_terms($post->ID, 'custom_casestudies');
?>
<div class="block-wrap mix<?php foreach ($terms as $term) echo ' ' . $term->slug ?>">
// content
</div>
<?php endwhile; wp_reset_postdata(); ?>
The terms have been to be after the while
loop.
Upvotes: 1
Reputation: 1028
get_terms returns all of the terms in the given taxonomy. In this case you should be using wp_get_post_terms, which returns a list of terms for a given post. The documentation goes into more detail.
Upvotes: 1