0

I have two custom taxonomies "products" & "products-info" registered for custom post type "products-posts".

There are three terms (shoes, shirts, pants) in "products". Similarly, there are two terms (color, size) in "products-info".

<?php
$args = array(
    'post_type'             => 'products-posts',
    'posts_per_page'        => 5,
    'orderby'               => 'date',
    'post__not_in'          => array( $post_id ),
    'ignore_sticky_posts'   => 1,
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'products',
            'field'    => 'slug',
            'terms'    => array('shoes'),
            'operator' => 'IN',
        ),
        array(
            'taxonomy' => 'products-info',
            'field'    => 'slug',
            'terms'    => array('color', 'size'),
            'operator' => 'IN',
        )
    )
);

$my_query = new WP_Query( $args );
while( $my_query->have_posts() ) { $my_query->the_post();
    the_title();
}
wp_reset_postdata();
?>

There are 5 posts:

  • post 1 is in three terms (shoes, color, size).
  • post 2 is in one terms (color).
  • post 3 is in one term (size).
  • post 4 is in one term (shirts).
  • post 5 is in one term (pants).

Now I'm visiting/on post 1.

What I'm expecting: there should be related two posts (post 2 & post 3).

What I'm getting is: all 4 posts excluding current. As you can see, the terms "shirts & pants" are not specified in query args. Then why it is showing post 4 & post 5.

here is SQL query:

Last SQL-Query: SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND wp_posts.ID NOT IN (10239) AND ( wp_term_relationships.term_taxonomy_id IN (136) OR wp_term_relationships.term_taxonomy_id IN (134,135) OR wp_posts.ID NOT IN ( SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (129) ) ) AND wp_posts.post_type = 'products-posts' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 5

Following is culprit: OR wp_posts.ID NOT IN ( SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN (129)

term id "129" belongs to WordPress default categories. As you can see, I did not specified default WordPress Category taxonomy in my query args. This is causing unexpected behavior. I don't know where it is coming from. Still I'm unable to solve this problem .

  • And what SQL query do you get from this WP_Query? – Krzysiek Dróżdż Aug 17 '19 at 6:12
  • 1
    @KrzysiekDróżdż question updated with right sql query. – samar Aug 17 '19 at 8:53

Your Answer

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

Browse other questions tagged or ask your own question.