Recently, I got some tutorial request via my blog, so that I am going to create a tutorial to solve the issue asked by that guys. The question is “How to Combining Two WP_Query in One Main Query”. Sometimes we need to perform the two condition and merge in one WP_Query to display the result on the front end website.
Below is the simple tutorial to merge the two WP_Queries in one WP_Queries and display the result. Copy the below code and change it as per your requirement. This is simple and easy code, In the below code I have used the
array_merge() function to merge the two array.
$args = array( 'post_type' => 'post' , 'posts_per_page' => 6 );
$wp_query = new WP_Query( $args );
$args1 = array(
'post_type' => 'books' ,
'meta_query' => array(
'numberposts' => -1,
'post_type' => 'books',
'key' => 'pubblic_in_home', // name of custom field
'value' => '1', // matches exaclty "red", not just red. This prevents a match for "acquired"
'compare' => '=='
$wp_query_args1 = new WP_Query( $args1 );
$result = new WP_Query();
// start putting the contents in the new object
$result->posts = array_merge( $wp_query->posts, $wp_query_args1->posts );
// here you might wanna apply some sort of sorting on $result->posts
// we also need to set post count correctly so as to enable the looping
$result->post_count = count( $result->posts );
I hope this tutorial helped you. If you still need any help, feel free to add your comments in below comment section. I will be happy to help.
Do you like & share this article with your friends, and don’t forget to follow us on Facebook and Twitter to learn cool WordPress tutorials and also don’t forget to subscribe my blog to get all future tutorials directly in your mail box.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: woocommerce plugin wordpress tutorial, wordpress merge 2 queries, wordpress tutorial, wordpress tutorial for beginner, wordpress tutorial for beginners, wordpress tutorials, wordpress tutorials for beginners, wordpress tutorils