I’m trying to show my CPT Category along with any posts associated with it below the title. I have the first loop fine:
<?php $cats = get_categories(array('taxonomy' => 'custtax', 'orderby' => 'term_group'));
if(!empty($cats)) :
foreach($cats as $cat) : ?>
<a href="<?php echo get_category_link($cat->term_id); ?>"><?php echo $cat->name; ?></a>
<br />
<?php wp_reset_query(); ?>
<?php $cat_posts = new WP_Query(array('post_type' => 'custcpt', 'taxonomy' => 'custtax', 'terms' => $cat->slug, 'order' => 'ASC'));
foreach($cat_posts as $cat_post) : ?>
<center><?php get_the_post_thumbnail($cat_post->ID, 'thumbnail'); ?></center>
<br />
<a href="<?php get_permalink($cat_post->ID); ?>"><?php get_the_title($cat_post->ID); ?></a>
<br />
<br />
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
But my second loop queries all my posts instead of just the ones from that category. I’ve tried get_posts()
and instead of pulling all posts it didn’t pull any. I’m not sure if 'category'
in the codex is expecting a string, slug, or ID, but I’ve tried all 3. Anyway how do I edit my query to only pull posts from that certain category?
To expand on the answer from @s_ha_dum – you need to modify a few things about your query.
First, use his suggested tax query:
Then, modify your code as follows:
Note a few things:
while ($cat_posts->have_posts)
to iterate over theposts.
cat_posts->the_post()
to prepare the data to be displayed in the functions such asget_the_title()
$cat_posts->post->ID
get_the_title()
, you do not need to pass the ID in.You need a
tax_query
and what you have is not that.