1

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

Here is an example:

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(); ?>
2

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();
}
  • This seems to work perfectly! Wish I knew why, but I'm happy it works:) – Jacob Oct 27 '13 at 16:46
  • @Jacob to understand the fucntion you need some SQL knowledge... I can say that the query get post from database assuring every post has a different taxonomy term. This is done via GROUP BY $wpdb->term_relationships.term_taxonomy_id. To explain how all the query works I should write some page, not an answer ;) Howerver, I'm happy it works, too. – gmazzap Oct 27 '13 at 16:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.