Last active
November 9, 2021 16:56
-
-
Save Jany-M/c0c712221934ea6898fb to your computer and use it in GitHub Desktop.
[WP] Merge Multiple Queries / Loops into one
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 | |
// 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(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ?