Query Posts but only return 1 from a custom taxonomy?

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();
}

Leave a Comment