Query Posts but only return 1 from a custom taxonomy?

I want to query my posts and only return one post from a custom taxonomy. Is this possible?

Here is an example:

Read More

I have a custom taxonomy called Author. I have 200 posts with various authors. I want to query and display 6 posts, but I don’t want the same author ever repeated within the query. This is my query below. Thanks!

<?php $args = array('posts_per_page' => 6, 'orderby' => 'rand');
                $taximg_loop = new WP_Query( $args );
                while ( $taximg_loop->have_posts() ) : $taximg_loop->the_post();?>
<?php endwhile; ?>
            <?php wp_reset_postdata(); ?>

Related posts

1 comment

  1. I think that using standard WP_Query you should run 6 different loops, but this is overwhelming. But using a custom $wpdb query you can do the trick…

    function get_unique_posts_tax( $taxonomy = 'category', $number = 10, $cpt = 'post') {
      global $wpdb;
      return $wpdb->get_results( $wpdb->prepare(
        "SELECT p.* FROM $wpdb->term_relationships
        JOIN $wpdb->term_taxonomy AS tt 
        ON tt.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
        JOIN $wpdb->posts AS p ON p.ID = $wpdb->term_relationships.object_id
        WHERE tt.taxonomy = %s
        AND p.post_type = %s AND p.post_status = 'publish'
        GROUP BY $wpdb->term_relationships.term_taxonomy_id
        ORDER BY RAND() LIMIT %d", $taxonomy, $cpt, $number
      ) );
    }
    

    Put this function in functions.php after that, you can

    $loop = get_unique_posts_tax( 'author', 6 );
    
    if ( ! empty($loop) ) {
      global $post;
      foreach ( $loop as $post ) {
        setup_postdata($post);
    
        // Here goes your loop content...
        echo '<p>' . get_the_title() . '</p>';
    
      }
      wp_reset_postdata();
    }
    

Comments are closed.