1

I would like to 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.

If I had this code:

$args['tax_query'] = array(
    array(
        'taxonomy' => 'cities',
        'terms' => array('Boston', 'Chicago'),
        'field' => 'slug',
        'operator' => 'NOT IN',
    ),
);
query_posts($args);

How can I pass to the terms array the checkboxes value? I mean, to change:

'terms' => array('Boston', 'Chicago'),

to:

'terms' => array(VALUE CHECKBOX 1, VALUE CHECKBOX 2),

Thanks.

0

1 Answer 1

0

You can run a query with a tax_query parameter which excludes certain taxonomy terms. See this answer.

As for where to run the query, you can either have a form that submits to the page it's on (you'll need to locate an appropriate template file being called for that page or create a custom one) and then, once the page refreshes, process your form inputs, run your query, and show results.

Alternatively, you can run your query on the server side and call it via AJAX. For more info on that you can start here (it talks about plugins but you don't really need to create a plugin, you can always put your PHP code into functions.php inside the theme directory) or just search around for tutorials on implementing AJAX in WordPress.

EDIT: as per your comment, here's some code to get value from checkbox on the page. It's untested, intended only as a guide. Notice that the form submits to itself, we achieve it with putting the page URL into the form's action parameter.

<?php
$cb_city = '';
if(isset($_POST['city']) && $_POST['city'] != '') { // if form was submitted we can get value
    $cb_city = $_POST['city'];
}
?>
<form action="<?php echo get_permalink(); ?>" method="POST">
    <label>Your label
        <?php
            $checked = "";
            if( !empty($cb_city) ){ // pre-populate checkboxif it was checked on form submit
                $checked = "checked";
            }
        ?>
        <input <?= $checked; ?> type="checkbox" name="city" id="city" value="1"/>
    </label>
    <button type="submit" class="btn-submit">Submit</button>
</form>
1
  • Thanks for your answer, but how can I pass the checkbox value to the terms array?
    – Mike
    Apr 26, 2013 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.