Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress tax_query where taxonomy is blank

Im using multiple taxonomy query to get relevant posts

    $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 post is tagged with transfer_type and an area there is no problem, But when a post is only tagged with one of them the results are wrong.

I basically (in some cases) want to exclude all posts that have an "area" or "transfer_type" and get only those that meet up with the other.

is it possible ?

like image 893
lior r Avatar asked Oct 22 '22 07:10

lior r


1 Answers

figured it out ... (don't know if it is the best but it still is a solution)

In case one of the taxonomies is empty im using the "NOT IN" operator on the entire taxonomy terms

        $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'
        );
like image 163
lior r Avatar answered Oct 28 '22 21:10

lior r