Dynamically tax_query

I have this for example:

$myquery['tax_query'] = array(
    'relation' => 'OR',
    array(
        'taxonomy' => 'cities',
        'terms' => 'boston',
        'field' => 'slug',
        'operator' => 'NOT IN'
    ),
    array(
        'taxonomy' => 'cities',
        'terms' => 'chicago',
        'field' => 'slug',
        'operator' => 'NOT IN'
    ),
);
query_posts($myquery);

But I would like to make it dinamically, because I have a form with checkboxes. Each checkbox would be a term of my taxonomy “cities”. The idea is that if a user select any of the checkboxes, it should show all posts that are NOT in marked terms. But I would like to generate as many arrays for tax_query as checkboxes selected.
I mean: If a user check Boston, I create:

Read More
array(
            'taxonomy' => 'cities',
            'terms' => 'boston',
            'field' => 'slug',
            'operator' => 'NOT IN'
        ),

If a user check Chicago:

array(
            'taxonomy' => 'cities',
            'terms' => 'chicago',
            'field' => 'slug',
            'operator' => 'NOT IN'
        ),

If a user check both of them:

array(
            'taxonomy' => 'cities',
            'terms' => 'boston',
            'field' => 'slug',
            'operator' => 'NOT IN'
        ),
        array(
            'taxonomy' => 'cities',
            'terms' => 'chicago',
            'field' => 'slug',
            'operator' => 'NOT IN'
        ),

How can I do it?

Related posts

Leave a Reply

1 comment

  1. Just needs a little array manipulation.

    $def = array(
        'taxonomy' => 'cities',
        'field' => 'slug',
        'operator' => 'NOT IN'
    );
    
    $cities = array(
        'boston',
        'chicago'
    );
    
    $args = array('relation' => 'OR');
    
    foreach ($cities as $c) {
         $args[] = wp_parse_args(array('terms'=>$c),$def);
    }
    print_r($args); 
    

    The $cities array you need to build from your $_POST or $_GET form data, or just create the $args array as you loop through the form data in the first place.