Combine two queries, one query after another

Viewed 40

I have two woocommerce queries, I want to display on the same page both queries, first the query with image and after the query without image, how do I merge them, so they will not mix?

        $argWithImage = array(
          'post_type' => 'product',
          'posts_per_page' => -1,
          'product_cat' => $queried_object->slug,
          'meta_key' => '_thumbnail_id',
        );

        $argWithoutImage = array(
          'post_type' => 'product',
          'posts_per_page' => -1,
          'product_cat' => $queried_object->slug,
          'meta_query' => array(
            array(
              'key' => '_thumbnail_id',
              'value' => '?',
              'compare' => 'NOT EXISTS'
            )
          ),
        );
    $merged_query_args = array_merge( $argWithImage, $argWithoutImage );

    $query = new WP_Query( $merged_query_args );
1 Answers

You need to execute each query separately in the same template file. You can't merge them in one query because their data is conflicting, do it like below:

$productsWithImage = new WP_Query( $argWithImage );
// The Loop
 while ( $productsWithImage->have_posts() ) : $productsWithImage->the_post();
 ?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br
/><?php 
 endwhile;
// Reset Post Data 
 wp_reset_postdata();

$productsWithoutImage = new WP_Query( $argWithoutImage );
// The Loop
 while ( $productsWithoutImage->have_posts() ) : $productsWithoutImage->the_post();
 ?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br
/><?php 
 endwhile;
// Reset Post Data 
 wp_reset_postdata();
Related