Getting only unique posts from a WordPress query

Viewed 16

I have a WordPress query that loops through a custom taxonomy category and pulls one post from each category, it then lists out all of the categories and displays the first posts featured image from each category as a display image.

This works perfectly with the help of someone here. However, since each post can be in multiple categories some categories are showing duplicate images. How would I go about ensuring each post/image is unique? This is easy enough in a normal WordPress query but this is kind of like two queries in one so I'm not sure the best way to achieve it. My current code is below:

    <?php
        $limit   = 999;
        $counter = 0;
        $cats    = get_terms(
            array(
                'taxonomy'   => 'categories',
                'hide_empty' => false,
            )
        );

        foreach ( $cats as $cat ) :
            if ( $counter < $limit ) {
                $args    = array(
                    'posts_per_page'      => 1,
                    'post_type'           => 'gallery',
                    'ignore_sticky_posts' => 1,
                    'tax_query'           => array(
                        array(
                            'taxonomy' => 'categories',
                            'terms'    => $cat->term_id,
                            'field'    => 'term_id',
                        ),
                    ),
                );
                $results = new WP_Query( $args );
                if ( $results->have_posts() ) {
                    echo '<div class="col-md-3 category-list">';
                    foreach ( $results->get_posts() as $the_post ) :
                        echo '<a href="' . esc_url( get_term_link( $cat->term_id, 'categories' ) ) . '"><div class="cat-list-img">';
                        $image = get_the_post_thumbnail( $the_post->ID, 'large' );
                        echo $image;
                        echo '<h5 class="cl-title">' . esc_attr( $cat->name ) . '</h5>';
                        echo '</div></a>';
                        echo '</div>';
                    endforeach;
                }
            }

            $counter++;
        endforeach;
        ?>
0 Answers
Related