Martin van Houte Martin van Houte - 3 months ago 14
PHP Question

Filtering the output with checkboxes in WordPress

I'm building a page in WordPress with a filter function. Basically I want to change the output of the data when you click on the checkbox. What I have now:

<form class="compo-filter">
<input type="checkbox" name="compo-cat" value="indoor" onclick="if(this.checked){this.form.submit();}" />Indoor
<input type="checkbox" name="compo-cat" value="outdoor" onclick="if(this.checked){this.form.submit();}" />Outdoor
<input type="checkbox" name="compo-cat" value="men" onclick="if(this.checked){this.form.submit();}" />Men
<input type="checkbox" name="compo-cat" value="women" onclick="if(this.checked){this.form.submit();}" />Women
<input type="checkbox" name="order" value="order" onclick="if(this.checked){this.form.submit();}" />Show only competitions currently in progress
</form>

<?php
$today = date('Y-m-d');
$args = array(
'post_type' => 'competitions',
'posts_per_page' => 10,
'meta_key' => 'startdate',
'meta_compare' => '>=',
'meta_value' => $today,
'orderby' => 'startdate',
'order' => 'ASC'
);
$args2 = array(
'post_type' => 'competitions',
'posts_per_page' => 10,
'meta_key' => 'startdate',
'orderby' => 'startdate',
'order' => 'ASC'
);

if ($_POST['order'] == 'order') {
$query = new WP_Query($args2);
} else {
$query = new WP_Query($args);
}

if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>


The above solution does however not work, and I'm not able to work out what's going wrong. The page reloads, and the URL is showing the selected value
/?order=order
.

Answer

I think the issue lies with the form method, you are using $_POST in the code but by putting the specific form method = "post" you can get this working in $_POST method.

By default without method attribute it will take you to the get method while submitting the form.

Comments