Wordpress tax_query where taxonomy is empty

Im using multiple taxonomy query to get matching messages

$tax_query[] = array( 'taxonomy' => 'transfer_type', 'field' => 'id', 'terms' => $page_terms['type_term'], 'include_children' => false ); $tax_query[] = array( 'taxonomy' => 'area', 'field' => 'id', 'terms' => $page_terms['area_term'], 'include_children' => false ); $args = array( 'post_type' => 'category_description', 'tax_query' => $tax_query ); $description_post = get_posts($args); 

When a message is marked with the transfer_type parameter and the area, there is no problem, but when a message is marked with only one of them, the results are erroneous.

I basically (in some cases) want to exclude all messages that have "area" or "transfer_type", and get only those that meet with another.

Is it possible?

+4
source share
1 answer

figured it out ... (I don’t know if this is better, but still this is a solution)

In case one of the taxonomies is empty, using the "NOT IN" operator on all taxonomic conditions

  $terms = get_terms("transfer_type"); foreach($terms as $term){ $not_in_type[] = $term->term_id; } $terms = get_terms("area"); foreach($terms as $term){ $not_in_area[] = $term->term_id; } $tax_query[] = array( 'taxonomy' => 'transfer_type', 'field' => 'id', 'terms' => $page_terms['type_term'] ? $page_terms['type_term'] : $not_in_type, 'include_children' => false, 'operator' => $page_terms['type_term'] ? 'IN' : 'NOT IN' ); $tax_query[] = array( 'taxonomy' => 'area', 'field' => 'id', 'terms' => $page_terms['area_term'] ? $page_terms['area_term'] : $not_in_area, 'include_children' => false, 'operator' => $page_terms['area_term'] ? 'IN' : 'NOT IN' ); 
+2
source

Source: https://habr.com/ru/post/1487834/


All Articles