Отображение всех постов пользовательского типа, сгруппированных по пользовательской таксономии.
Часто возникает ситуация, когда нам нужно вывести все посты пользовательского типа, сгруппированных по пользовательской таксономии.
Допустим, пользовательский тип записи называется member
, а пользовательская таксономия называется member_groups
. Задача перечислить всех участников, но сгруппировать их в соответствующие группы.
<?php
$member_group_terms = get_terms( 'member_group' );
foreach ( $member_group_terms as $member_group_term ) {
$member_group_query = new WP_Query( array(
'post_type' => 'member',
'tax_query' => array(
array(
'taxonomy' => 'member_group',
'field' => 'slug',
'terms' => array( $member_group_term->slug ),
'operator' => 'IN'
)
)
) );
?>
<h2><?php echo $member_group_term->name; ?></h2>
<ul>
<?php
if ( $member_group_query->have_posts() ) : while ( $member_group_query->have_posts() ) : $member_group_query->the_post(); ?>
<li><?php echo the_title(); ?></li>
<?php endwhile; endif; ?>
</ul>
<?php
// Reset things, for good measure
$member_group_query = null;
wp_reset_postdata();
}
Или так:
<?php // Output all Taxonomies names with their respective items
$terms = get_terms('member_groups');
foreach( $terms as $term ):
?>
<h3><?php echo $term->name; // Print the term name ?></h3>
<ul>
<?php
$posts = get_posts(array(
'post_type' => 'member',
'taxonomy' => $term->taxonomy,
'term' => $term->slug,
'nopaging' => true, // to show all posts in this taxonomy, could also use 'numberposts' => -1 instead
));
foreach($posts as $post): // begin cycle through posts of this taxonmy
setup_postdata($post); //set up post data for use in the loop (enables the_title(), etc without specifying a post ID)
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>