I use $_POST form to get multiple elements from a form. The main problem is when I have multiple "if statements". It can become a true mess with nested statements when I want to check if multiple strings exist...
$cat = // Categories
if(!empty($cat)) {
$args = array(
'post_type' => 'domains',
'post_status' => 'publish',
'tax_query' => array(
array (
'taxonomy' => 'domain_categories',
'field' => 'slug',
'terms' => $cat, // ELEMENT EXISTS FOR $cat
),
),
);
} else { // ELSE STATEMENT IF $cat DOESN'T EXIST
$args = array(
'post_type' => 'domains',
'post_status' => 'publish',
);
} // END STATEMENT FOR $cat
So, I would like to be able to simplify this.
I use $_POST form to get multiple elements from a form. The main problem is when I have multiple "if statements". It can become a true mess with nested statements when I want to check if multiple strings exist...
$cat = // Categories
if(!empty($cat)) {
$args = array(
'post_type' => 'domains',
'post_status' => 'publish',
'tax_query' => array(
array (
'taxonomy' => 'domain_categories',
'field' => 'slug',
'terms' => $cat, // ELEMENT EXISTS FOR $cat
),
),
);
} else { // ELSE STATEMENT IF $cat DOESN'T EXIST
$args = array(
'post_type' => 'domains',
'post_status' => 'publish',
);
} // END STATEMENT FOR $cat
So, I would like to be able to simplify this.
Share Improve this question edited Mar 19, 2020 at 9:46 user3492770 asked Mar 19, 2020 at 9:21 user3492770user3492770 771 silver badge8 bronze badges 1- I found a solution here : wordpress.stackexchange/questions/55831/… – user3492770 Commented Mar 19, 2020 at 9:44
1 Answer
Reset to default 1As said here : Conditional arguments for WP_Query and tax_query depending on if $somevar has a value
I can define the args outside of the WP_Query instantiation:
<?php
$tax_query = array('relation' => 'AND');
if (isset($search_course_area))
{
$tax_query[] = array(
'taxonomy' => 'course-area',
'field' => 'id',
'terms' => $search_course_area
);
}
if (isset($search_course_level))
{
$tax_query[] = array(
'taxonomy' => 'study-levels',
'field' => 'id',
'terms' => $search_course_level
);
}
if (isset($search_course_mode))
{
$tax_query[] = array(
'taxonomy' => 'course-mode',
'field' => 'id',
'terms' => $search_course_mode
);
}
$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' => $tax_query,
)
);
?>