I have two taxonomies setup, one called “Article Category” and “Article Sub Category”. I would like each to have a dropdown with their terms listed and works fine using the code below, which is an example of the first dropdown:
<div class="col-12 col-md-2" data-aos="fade-up">
<?php
$terms = get_terms([
'taxonomy' => 'article-category',
'hide_empty' => false,
]);
$term_ids = wp_list_pluck($terms, 'term_id');
echo '<select class="form-select service-area-select" aria-label="Search by Service Area">';
echo '<option value="0" selected>Search by Service Area</option>';
foreach ($terms as $term) {
$args_products_category = array(
'post_type' => 'advice-and-article',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'article-category',
'field' => 'term_id',
'terms' => $term_ids,
),
),
);
$loop_products_category = new WP_Query($args_products_category);
echo '<option value="'.$term->term_id.'">'.$term->name.'</option>';
}
echo '</select>';
?>
</div>
Now, we’re using some AJAX so when the select field is changed, it alters the query to only bring through posts that match the selected term id. Again, this works fine using the code below as an example (The “Our Code Here” comment is just where our loop code goes):
function wow_query_advice_ajax_function() {
$service_area_select = $_POST['service_area_select'];
$category_select = $_POST['category_select'];
ob_start();
$args = array(
'post_type' => 'advice-and-article',
'post_status' => 'publish',
'posts_per_page' => 9,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'article-category',
'field' => 'term_id',
'terms' => array($service_area_select),
'compare' => 'LIKE',
),
array(
'taxonomy' => 'article-sub-category',
'field' => 'term_id',
'terms' => array($category_select),
'compare' => 'LIKE',
)
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$advice_output = 'OUR CODE HERE';
endwhile;
wp_reset_postdata();
echo $advice_output;
echo ob_get_clean();
exit;
}
add_action('wp_ajax_wow_query_advice_ajax_function', 'wow_query_advice_ajax_function');
add_action('wp_ajax_nopriv_wow_query_advice_ajax_function', 'wow_query_advice_ajax_function');
What needs to be fixed somehow, is after we select a term from the dropdown, if we decide to then cancel the selection by selecting the “Search by Service Area” from the list, it returns nothing, whereas we would like it to return everything.
We’ve tried setting the value to “0” and “”, but whatever we try, it doesn’t return everything. I’m assuming that’s because it’s trying to find “term_ids” LIKE 0 but ofcourse this doesn’t exist. So how can we reset the filter by choosing the first again?
Any help would be much appreciated, thanks!