0

I have Custom Post Type (Courses) with a field "course-location" that is a checkbox. I would like to filter the listing page with the checked items.

The below code is working when I select ONE checkbox, however, it is not working with multiple-checked items.

How can I have

OR statement

working to return many courses?

CODE

$searchArray = array();
$searchArray[] = array('relation' => 'OR',);

// loop over checked checkboxes
if(!empty($_POST['course_location'])) {
    foreach($_POST['course_location'] as $check) {
        // echo '<h1>'.$check.'</h1>'; 
        $searchArray[] = array('key' => 'course_location','value' => $check,'compare' => 'LIKE',);
    }
}

$args = array(
    'post_type' => array( 'course' ),
    'posts_per_page' => 25,
    'meta_query' => $searchArray
    );

$wp_query = new WP_Query($args);

FORM

<form name="courseSearch" id="courseSearch" method="post">
los-angeles-county: <input type="checkbox" name="course_location[]" value="los-angeles-county" /><br/>
orange-county: <input type="checkbox" name="course_location[]" value="orange-county" /><br/>
test: <input type="checkbox" name="course_location[]" value="test" /><br/>
<input type="submit">
</form>
1
  • You can't query by "checkboxes" - can you clarify if these attributes are taxonomy terms or post meta? Nov 4, 2015 at 13:50

1 Answer 1

2

You aren't constructing the meta_query correctly. It is close but not quite right.

$searchArray = array();
$searchArray = array('relation' => 'OR',); // here is the change

// loop over checked checkboxes
if(!empty($_POST['course_location'])) {
    foreach($_POST['course_location'] as $check) {
        // echo '<h1>'.$check.'</h1>'; 
        $searchArray[] = array('key' => 'course_location','value' => $check,'compare' => 'LIKE',);
    }
}

As you have it written you were getting:

array(3) {
  [0]=>
  array(1) {
    ["relation"]=>
    string(2) "OR"
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(15) "course_location"
    ["value"]=>
    string(1) "a"
    ["compare"]=>
    string(4) "LIKE"
  }
  [2]=>
  array(3) {
    ["key"]=>
    string(15) "course_location"
    ["value"]=>
    string(1) "b"
    ["compare"]=>
    string(4) "LIKE"
  }
}

And you need:

array(3) {
  ["relation"]=>
    string(2) "OR"
  [0=>
  array(3) {
    ["key"]=>
    string(15) "course_location"
    ["value"]=>
    string(1) "a"
    ["compare"]=>
    string(4) "LIKE"
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(15) "course_location"
    ["value"]=>
    string(1) "b"
    ["compare"]=>
    string(4) "LIKE"
  }
}
1
  • Thanks - changing the initial array setup worked. I used echo '<pre>'; print_r($searchArray); echo '</pre>'; to dump the array to screen.
    – Ravi Ram
    Nov 5, 2015 at 13:54

Your Answer

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

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