I’ve created a new query for a custom post type of ‘courses’. Those results are then to be filtered using tax_query, querying 3 custom taxonomies matching 1 or several term ID’s. These are passed from a search page.
Here’s the code working find up to now:
// Lets emulate the posted ID's from the course search widget
// with some static term ID's for each custom taxonomy.
$search_course_area = array(65, 62);
$search_course_level = array(117); //52 for further filtering
$search_course_mode = array(54, 56);
//Begin a new query
$query = new WP_Query(
array(
//Retreive ALL course posts
'post_type' => 'course',
'posts_per_page' => '-1',
//Filter taxonomies by id's passed from course finder widget
'tax_query' => array(
//Set the relation condition for the filters in
//this case we're using AND as it is explicity set
//by the user when searching
'relation' => 'AND',
//First check retreive course-area's based on ID
array(
'taxonomy' => 'course-area',
'field' => 'id',
'terms' => $search_course_area
),
//And again for the second taxonomy
array(
'taxonomy' => 'study-levels',
'field' => 'id',
'terms' => $search_course_level
),
//Finally check retreive course-level's based on ID
array(
'taxonomy' => 'course-mode',
'field' => 'id',
'terms' => $search_course_mode
),
)
)
);
The thing I’m a little stuck on, is if an array is passed which is empty, this would obviously break the query and return no results.
What would be the cleanest way to tackle this? I could do something like:
if (isset($search_course_area)) {
echo "array(
'taxonomy' => 'course-area',
'field' => 'id',
'terms' => $search_course_area
),";
};
But I have a feeling that wouldn’t be the best way to approach it?
Thanks a lot for your time and any help you can give I really appreciate it!
You can define the args outside of the
WP_Query
instantiation:Just in case if someone is seeing this nowadays, if you have multiple cases within your query instance you should have your variable wrapped by another array.. something like: