简体   繁体   中英

get posts within get_terms loop

I have a basic loop set up to display all terms in a custom taxonomy.

<?php   
$workshops = get_terms( 'workshop', array(
    'orderby'    => 'name',
    'hide_empty' => 0,
) );
foreach ( $workshops as $workshop ) { ?>

        <h3><?php echo $workshop->name; ?></h3>         
        <?php echo term_description($workshop); ?>                     

<?php } ?>

How can I display all posts for each respective term within that loop?

For example..

Taxonomy is Movies. Terms are Comedy, Horror, etc.

I'd like output to be

Comedy Description for comedy term

  • Movie 1
  • Movie 2

Horror Description for horror term

  • Movie 3
  • Movie 4

Thanks! Rich

First off, you are using a deprecated version of get_terms so we should fix that first:

$workshops = get_terms( array(
    'taxonomy' => 'workshop',
    'orderby' => 'name',
    'hide_empty' => false
) );

Then, within your term loop, you need to create another query to grab all the posts that fall under the term:

$query = new WP_Query( array(
    'post_type' => 'post',  // Or your custom post type's slug
    'posts_per_page' => -1, // Do not paginate posts
    'tax_query' => array(
        array(
            'taxonomy' => 'workshop',
            'field' => 'term_id',
            'terms' => $workshop->term_id
        )
    )
) );

Finally, still within your term loop, write another loop to build the lists of posts:

<?php if ( $query->have_posts() ): ?>
    <ul class="term-post-list" id="term-<?php echo $workshop->term_id; ?>-posts">

        <?php while ( $query->have_posts() ): $query->the_post(); ?>
            <li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <?php the_title(); ?>
            </li>
        <?php endwhile; wp_reset_postdata(); ?>

    </ul>
<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM