Looping Through Custom Tax Terms and Displaying All Posts For Each

If your things are laid properly, this code will output 10 posts from film CPT, where taxonomy is category-film and it will occur each of the term of that particular taxonomy. I’m not aware about your templating, so lay your layout accordingly.

<?php
$_terms = get_terms( array('category-film') );

foreach ($_terms as $term) :

    $term_slug = $term->slug;
    $_posts = new WP_Query( array(
                'post_type'         => 'film',
                'posts_per_page'    => 10, //important for a PHP memory limit warning
                'tax_query' => array(
                    array(
                        'taxonomy' => 'category-film',
                        'field'    => 'slug',
                        'terms'    => $term_slug,
                    ),
                ),
            ));

    if( $_posts->have_posts() ) :

        echo '<h3>'. $term->name .'</h3>';
        echo '<div class="row">';
        while ( $_posts->have_posts() ) : $_posts->the_post();
        ?>
            <div class="col-sm-6">
                <h4><?php the_title(); ?></h4>
                <p><?php echo get_post_meta( get_the_ID(), 'url', true ); ?></p>
            </div>
        <?php
        endwhile;

        echo '</div>';

    endif;
    wp_reset_postdata();

endforeach;
?>

Leave a Comment