Stickers
Stickers

Reputation: 78676

How to simplify multiple WP_Query with different meta values

Their are 6 total queries I need to use, below is list of 2 of them. Is it possible to simplify it? As you can see the key is the different values of meta_value, they are 1-6.

<?php
$args1 = array(
    'posts_per_page' => -1, 
    'post_parent' => $post->ID,
    'post_type' => 'page',
    'orderby' => 'date',
    'order' => 'ASC',
    'meta_key' => 'product_column',
    'meta_value' => 1
);

$the_query1 = new WP_Query($args1);

if ($the_query1->have_posts()) {
    while ($the_query1->have_posts()) {
        $the_query1->the_post();
        //do stuff
    }
}
wp_reset_postdata();
?>

<?php
$args2 = array(
    'posts_per_page' => -1, 
    'post_parent' => $post->ID,
    'post_type' => 'page',
    'orderby' => 'date',
    'order' => 'ASC',
    'meta_key' => 'product_column',
    'meta_value' => 2
);

$the_query2 = new WP_Query($args2);

if ($the_query2->have_posts()) {
    while ($the_query2->have_posts()) {
        $the_query2->the_post();
        //do stuff
    }
}
wp_reset_postdata();
?>

Upvotes: 1

Views: 216

Answers (1)

Talk nerdy to me
Talk nerdy to me

Reputation: 1085

If you just want to get all the posts with meta values 1-6, you can pass as array

$args1 = array(
    'posts_per_page' => -1, 
    'post_parent' => $post->ID,
    'post_type' => 'page',
    'orderby' => 'date',
    'order' => 'ASC',
    'meta_key' => 'product_column',
    'meta_value' => array( 1,2,3,4,5,6 )

);

$the_query1 = new WP_Query($args1);

Edited as per comments:

You could add the values to an array and run a foreach loop

$meta_values = array( 1,2,3,4,5,6 );

foreach ( $meta_values as $meta_value ) {

$args = array(
    'posts_per_page' => -1, 
    'post_parent' => $post->ID,
    'post_type' => 'page',
    'orderby' => 'date',
    'order' => 'ASC',
    'meta_key' => 'product_column',
    'meta_value' => $meta_value

);

$the_query = new WP_Query($args);

if ($the_query->have_posts()) {
    while ($the_query->have_posts()) {
        $the_query->the_post();
        //...
    }
}
wp_reset_postdata();
}

Upvotes: 1

Related Questions