Last active
March 1, 2023 09:43
-
-
Save groucho75/5d15101e5f503d3fbb0d to your computer and use it in GitHub Desktop.
Merging results of 2 WP_Query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
Thank you very much. Thats what i needed
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
Not exactly what I needed, but let me see how I needed to merge the two queries, and it worked. Thanks for the gist.