How do I create a WP_Query that combines two queries and orders by category?

Tips and tricks from Tamara Olson Designs

The design dictated that there be a paginated list of posts that started with posts from the primary category, and then drew from a custom taxonomy. Not going to lie. This was a doozy.


// set the "paged" parameter (use 'page' if the query is on a static front page)
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
// Get the first query - all microsite posts
$posts1 = get_posts(array(
'category_name' => 'combined',
'posts_per_page' => -1
));
// Get the second query - all posts tagged with microsite
$posts2 = get_posts(array(
'post_type' => 'post',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'otherposts',
'field' => 'slug',
'terms' => 'combined'
)
)
));
// Combine the queries
$mergedposts = array_merge( $posts1, $posts2 );
$postids = array();
foreach( $mergedposts as $item ) {
$postids[]=$item->ID; //create a new query only of the post ids
}
// Create an array of post IDs
$uniqueposts = array_unique($postids);
$args3 = array(
'post__in' => $uniqueposts,
'paged' => $paged,
'orderby' => 'post__in'
);
$the_query = new WP_Query($args3);
if ( $the_query->have_posts() ) {
$checking = 0;
while ( $the_query->have_posts() ) {
$the_query->the_post();


Share Your Thoughts

About the Author

TamaraAuthorPhoto

Tamara Olson is a self-employed UX designer and WordPress developer living in New York City.

Tamara Olson Designs Case Studies