In my Query, I’m having trouble displaying the data the way I want.
I have a custom post type with categories (custom taxonomy) that have child categories. For example:
Adults
- sports
- music
Teens
- games
- music
I have a page for each parent category (Adults, Children, etc.) in which I want to list the posts grouped by child category. For example, in the Adults page, I will have all the posts of the Adults category. These posts will be grouped by child category (sports, music, etc). For example:
Adults page (only displays posts in the Adult category)
Sports
- post 1
- post 2
Music
- post 3
- post 4
Teens page (only displays posts in the Teens category)
Games
- post 5
- post 6
Music
- post 7
- post 8
I managed to get my query to work, but it prints out all the posts regardless of categories:
Adults (page)
Adults (category – should not be displayed)
- post 1
- post 2
- post 3
- post 4
Sports
- post 1
- post 2
Music
- post 3
- post 4
Teens (from here to the end – should not be displayed in Adults page)
- post 5
- post 6
- post 7
- post 8
Games
- post 5
- post 6
Music
- post 7
- post 8
It seems the taxonomy terms are not added correctly. Here is my query so far:
<?php
/**
*
* Loop through some custom post types and group them by taxonomy term,
* outputting the taxonomy term names before the set of posts
*
*/
// get all of the custom taxonomy terms
$taxonomy = 'groupe';
$args = array(
'orderby' => 'id',
'order' => 'ASC',
'term' => 'adultes',
);
$taxonomy_terms = get_terms($taxonomy, $args);
// if there are some taxonomy terms, loop through each one and get the posts in that term
if($taxonomy_terms) {
foreach($taxonomy_terms as $taxonomy_term) {
$args = array(
'post_type' => 'activite',
"$taxonomy" => $taxonomy_term->slug,
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : ?>
<!-- output the taxonomy name for the current term -->
<h2><?php echo $taxonomy_term->name; ?></h2>
<div class="cpts-wrap">
<!-- loop over the posts -->
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile; ?>
</div><!-- .cpts-wrap -->
<?php wp_reset_postdata(); // so nothin' weird happens to other loops
endif;
}
}
?>
Thanks for any help!
2
Answers
Sorry for late response. Turns out i was completeley wrong. Since I'm listing custom post types and not pages. All I have to do is create a taxonomy template (and not a page template). That takes care of the first taxonomy level. All that is left is group activities by sub categories.
Here's my code
Given, this is the archive page for the given taxonomy the below code should work