Skip to content

Instantly share code, notes, and snippets.

@groucho75
Last active March 1, 2023 09:43
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groucho75/5d15101e5f503d3fbb0d to your computer and use it in GitHub Desktop.
Save groucho75/5d15101e5f503d3fbb0d to your computer and use it in GitHub Desktop.
Merging results of 2 WP_Query
<?php
/**
* Case: related news
*
* At first query for posts of same category, then, if it doesn't find enough posts, query for other posts and merge the 2 results.
*
* Put the following code inside a single template.
*
* @link Inspired by http://wordpress.stackexchange.com/questions/71576/combining-queries-with-different-arguments-per-post-type#answer-71582
*/
// First query: latest 3 posts of same category
$args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'category__in' => wp_get_post_categories( $post->ID ),
'post__not_in' => array( $post->ID ),
);
$my_query = new WP_Query( $args );
// Less than 3 posts? Query for more posts of any categories
if ( $my_query->post_count < 3 ) {
$related_ids = array_map( function( $v ) {
return $v->ID;
}, $my_query->posts );
$args = array(
'post_type' => 'post',
'posts_per_page' => 3 - $my_query->post_count,
'post__not_in' => array_merge( array( $post->ID ), $related_ids ),
);
$more_query = new WP_Query( $args );
$my_query->posts = array_merge( $my_query->posts, $more_query->posts );
$my_query->post_count = count( $my_query->posts );
}
if ( $my_query->have_posts()) :
while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<?php the_title(); ?><br />
<?php endwhile;
endif;
wp_reset_postdata();
@geniuswebtools
Copy link

Not exactly what I needed, but let me see how I needed to merge the two queries, and it worked. Thanks for the gist.

@rakibulmuhajir
Copy link

Thank you very much. Thats what i needed

@BFranklinAmsive
Copy link

Thank you so much. Exactly the starter I needed to knock out a component of a project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment