0
votes

I want to build a dynamic set of arguments for a wp_query but have had real problems doing this. Take the following example code (which does work)...

$args = array(
    'numberposts' => -1,
    'posts_per_page' => -1,
    'post_type' => 'skills',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'years',
            'value' => 'Primary',
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'years',
            'value' => 'Secondary',
            'compare' => 'LIKE'
        )
    )
);

// get results
$the_query = new WP_Query( $args );

The idea is that depending on the results of user input in a form, the number of clauses in my meta_query value would alter. In the code above there are two options, but maybe depending on input there are 3 or another time 5.

I tried compiling these inner array elements externally of $args. Assume in following code that $inputArray is a single dimensional array of string elements. The test looked like:

$inputArray=array();
if (is_array($yearsArray)){
    foreach( $yearsArray as $year ) {
        $inputArray[]=array('key' => 'years','value' => $year,'compare' => 'LIKE');
    }
}



// args
$args = array(
    'numberposts' => -1,
    'posts_per_page' => -1,
    'post_type' => 'skills',
    'meta_query' => array(
        'relation' => 'OR',
        $inputArray
    )
);

But the query just runs as if no meta_query queries had been applied.

I also tried using the function wp_parse_args to try and merge multiple meta_queries, however it seems that I'm overwriting the value and only the last one is ever used. This looked like this:

// args
$args = array(
    'numberposts' => -1,
    'posts_per_page' => -1,
    'post_type' => 'skills'

);

$args2 = array(
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'years',
            'value' => 'Secondary',
            'compare' => 'LIKE'
        )
    )
);
$args3 = array(
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'years',
            'value' => 'Primary',
            'compare' => 'LIKE'
        )
    )
);

$args=wp_parse_args($args,$args2,$args3);

So as you can see I've tried a few different methods but none are working. Can anyone assist?

1

1 Answers

0
votes

I fixed this by discovering that you can use IN as a compare clause. $yearsArray was just a single dimensional array of string values.

$args = array(
    'numberposts' => -1,
    'posts_per_page' => -1,
    'post_type' => 'skills',
    'meta_query' => array(
        array(
            'key' => 'years',
            'value' => $yearsArray,
            'compare' => 'IN'
        )
    )
);