0

I have this query

$query->set( 'tax_query', array(
                    'relation' => 'OR',
                    array(
                        'taxonomy' => 'location',
                         'operator' => 'IN',
                        'field' => 'slug',
                        'terms' => $availableRegions,
                    ),
                    array(
                        'taxonomy' => 'location',
                         'operator' => 'NOT IN',
                        'field' => 'slug',
                        'terms' => $notavailableRegions,
                    )
                ));

and it's return this sql query

SELECT wp_posts.ID
FROM wp_posts 
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id) JOIN wp_icl_translations t
ON wp_posts.ID = t.element_id 
AND t.element_type IN ('bla') JOIN wp_icl_languages l
ON t.language_code=l.code
AND l.active=1
WHERE 1=1  


AND (
wp_term_relationships.term_taxonomy_id IN (200) 

OR wp_posts.ID NOT IN ( 
SELECT object_id 
FROM wp_term_relationships 
WHERE term_taxonomy_id IN (201,203,205,206) )
)

but what i really need is to return this sql

SELECT wp_posts.ID
FROM wp_posts 
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id) JOIN wp_icl_translations t
ON wp_posts.ID = t.element_id 
AND t.element_type IN ('bla') JOIN wp_icl_languages l
ON t.language_code=l.code
AND l.active=1
WHERE 1=1  


AND (
wp_term_relationships.term_taxonomy_id IN (200) 
OR wp_term_relationships.term_taxonomy_id NOT IN (201,203,205,206) 

)

any suggestions to save my weekend :D

0

Let's say you have 5 instances: 200, 201, 202, 203, 204

NOT IN {200, 201, 202} is equal to IN {203, 204} (all the other instances).

So you don't need your IN operator anymore because its results are already included from using the NOT IN operator.

In your case, this logic works assuming an article does not have multiple locations.

$query->set('tax_query',

        array(
            array (
                'taxonomy' => 'location',
                'operator' => 'NOT IN',
                'field' => 'slug',
                'terms' => $notavailableRegions,
            )
        )
);
  • I have also post without any regions, i want to include them in this query – Bashar Gh Jul 7 '16 at 13:28
  • If they have no taxonomy, then you can't query them with 'tax_query' ... A solution that Wordpress itself adopts with its "Uncategorized" category for posts. You can create a "NoLocation" taxonomy yourself, and then the logic above works! Noting that in your question, nothing about posts without "locations" was mentioned. – P-S Jul 8 '16 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.