Skip to content

Instantly share code, notes, and snippets.

@Jany-M
Last active November 9, 2021 16:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Jany-M/c0c712221934ea6898fb to your computer and use it in GitHub Desktop.
Save Jany-M/c0c712221934ea6898fb to your computer and use it in GitHub Desktop.
[WP] Merge Multiple Queries / Loops into one
<?php
// Check if values are cached, if not cache them
//delete_transient('home_slider_24h');
if(get_transient('home_slider_24h') === false) {
// RM Blog (post) query
$rm_blog_args = array(
'posts_per_page' => 1,
'cat' => 10,
'post_type' => 'post'
);
$rm_blog = new WP_Query($rm_blog_args);
// F&B (post) query
$fb_args = array(
'posts_per_page' => 1,
'cat' => '463, -505',
'post_type' => 'post'
);
$fb = new WP_Query($fb_args);
// How-To (how-to) query
$howto_args = array(
'posts_per_page' => 1,
'post_type' => 'how-to'
);
$howto = new WP_Query($howto_args);
// Knowledge Base (knowledge-base) query
$kb_args = array(
'posts_per_page' => 1,
'post_type' => 'knowledge-base'
);
$kb = new WP_Query($kb_args);
// Final Query
$final_query = new WP_Query();
// Merging queries
$final_query->posts = array_merge( $rm_blog->posts, $fb->posts, $howto->posts, $kb->posts );
// Recount
$final_query->post_count = count( $final_query->posts );
// Cache Results
set_transient('home_slider_24h', $final_query, 24 * HOUR_IN_SECONDS );
// Remove duplicate post IDs
$post_ids = array();
foreach( $final_query->posts as $item ) {
$post_ids[] = $item->ID;
}
$unique_posts = array_unique($post_ids);
// Cache Duplicated Posts Results
//delete_transient('home_slider_duplicated_posts_24h');
if(get_transient('home_slider_duplicated_posts_24h') === false) {
set_transient('home_slider_duplicated_posts_24h', $unique_posts, 24 * HOUR_IN_SECONDS );
}
}
// Get cached results
$final_query = get_transient('home_slider_24h');
// Get posts to exclude
$posts_to_exclude = get_transient('home_slider_duplicated_posts_24h');
// Looping
if($final_query->have_posts()) : while ( $final_query->have_posts() ) : $final_query->the_post();
// post layout and output goes here...............
endwhile; endif; wp_reset_query(); wp_reset_postdata();
?>
@vguenichon
Copy link

This code is really great.
I tried this but with queries from different sites (in a multisite installation) and it doesn't return correct objects from the other sites using switch_to_blog to perform queries.
Do you have an idea on how to achieve that ?

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