Combining WordPress Post Queries With Options
Combining WordPress Post Queries With Options
Ah WordPress queries, how convenient and expandable they are. I’ve been working with some pretty big queries lately and I’ve been very impressed with how well WordPress has handled them. Very clean and very fast. Last week, I had the need to combine two post queries which I have done a couple times in the past, but this instance posed a second challenge: they needed to be re-ordered after combining. After thinking through several different options, here’s what I came up with. In short, we’re going to take two queries, merge the arrays, remove duplicates, and then re-query the posts using ‘post__in’. In the re-query, we can also set ordering rules. Let’s jump into the code:
Query 1:
$studentposts = get_posts(array( 'post_type' => 'student', 'post_status' => 'publish', 'cat' => 'books', ));
Query 2:
$busposts = get_posts(array( 'post_type' => 'business', 'post_status' => 'publish', 'cat' => 'wholesale', ));
Combine & Get Unique
$mergedposts = array_merge( $studentposts, $busposts ); $postids = array(); foreach( $mergedposts as $item ) { $postids[]=$item->ID; } $uniqueposts = array_unique($postids); //remove duplicate post ids
Re-Query With Order
if(!empty($uniqueposts)) { $args = array( 'post__in' => $uniqueposts, 'post_type' => 'any', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC' ); $the_query = new WP_Query( $args ); if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post(); // Do stuff here endwhile; endif; wp_reset_query(); }
And that’s how we can combine two post queries and then re-order them!
For those queries (1 & 2) I would use “fields” parameter to extract just the ids of the posts.
https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter
Thanks George! Definitely correct, adding a fields parameter would be more efficient.
if you need only IDs for query 1 & 2, I think you should be more efficient and get only IDs from database.
$studentposts = get_posts(array(
‘post_type’ => ‘student’,
‘post_status’ => ‘publish’,
‘cat’ => ‘books’,
‘fields’ => ‘ids’
));
$busposts = get_posts(array(
‘post_type’ => ‘business’,
‘post_status’ => ‘publish’,
‘cat’ => ‘wholesale’,
‘fields’ => ‘ids’
));
Thanks David, definitely correct, my mistake. Adding a fields parameter would definitely be more efficient.
You can do the same without the last query… just by sorting the two posts sub array with a sort function…