I'm currently working on a Wordpress-project which has to display all the categories, subcategories and posts within these subcategories of a custom post type & taxonomy. I should become something like this:
- Category 1
- subcategory
- post 1
- post 2
- subcategory
- post 3
- Category 2
- subcategory
- post 4
At this moment the code returns a list of all the categories and subcategories in the taxonomy between the h3-tags. Only the parent categories should be displayed here.
<?php
$terms = get_terms('resource_category', array('hierarchical' => false));
foreach ($terms as $term) {
$cat_slug = $term->slug;
$cat_id = $term->term_id;
$subcats = get_categories('child_of='.$cat_id.'&taxonomy=resource_category');
if ( have_posts() ) :
/* CATEGORY */ ?>
<div class="resources">
<?php echo '<h3>'.$term->name.'</h3>';
/* SUBCATEGORY */
foreach ($subcats as $subcat) {
if ( have_posts() ) :
echo '<h4>' . $subcat->name .'</h4>';
query_posts('post_type=resources&resource_category='.$subcat->cat_name.'&hide_empty=1'); ?>
<?php while ( have_posts() ) : the_post();
/* SUBCATEGORY POSTS */?>
<div class="resource-item">
<ul>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
</ul>
</div>
<?php endwhile; endif; wp_reset_query();} ?>
</div>
<?php endif; wp_reset_query(); } ?>
Big thanks if anyone can help me with this!
get_terms()
- you're telling it to not get heirarchical, but actually what you need to do is set it like so:array('parent'=>0)
, which will cause it to only get top-level terms. get_terms – random_user_name Feb 27 '14 at 3:11