Make WordPress Core

Opened 12 months ago

Last modified 12 months ago

#47802 new defect (bug)

WP_Query get_posts sometimes inserts contradictory taxonomy queries

Reported by: nstevensdc Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Query Keywords:
Focuses: Cc:


In our website, we have a custom taxonomy called 'section.' It figures prominently in a query we're doing. Here's a (lightly anonymized) dump of the array we pass to the WP_Query constructor, before calling get_posts() on the query created:

    [posts_per_page] => 25
    [post_type] => post
    [tax_query] => Array
            [0] => Array
                    [operator] => IN
                    [taxonomy] => section
                    [field] => slug
                    [terms] => Array
                            [0] => section1
                            [1] => section2
                            [2] => section3
                            [3] => section4


            [1] => Array
                    [operator] => NOT IN
                    [taxonomy] => section
                    [field] => slug
                    [terms] => Array
                            [0] => section5


            [relation] => AND

    [orderby] => post_date
    [order] => DESC

We had a problem where many posts that should be returned here, are not. After much digging, I found the problem in get_posts. specifically in the segment of code commented:

			 * Set 'taxonomy', 'term', and 'term_id' to the
			 * first taxonomy other than 'post_tag' or 'category'.

It's true, the code is doing just that. It's adding a taxonomy parameter. But it's picking up one of the sections that is supposed to be one of several possibilities the section can be IN, not required. It then makes that one single section required in an appended AND! Sample (again, lightly anonymized) SQL segment of the obviously self-contradictory conditions created (where 1001-1005 are the IDs corresponding to sections 1-5)

  wp_term_relationships.term_taxonomy_id IN (1001, 1002, 1003, 1004)
  wp_posts.ID NOT IN (
				SELECT object_id
				FROM wp_term_relationships
				WHERE term_taxonomy_id IN (1005)
  tt1.term_taxonomy_id IN (1001)

That third clause, the final IN (1001) is being added by get_posts in the above-commented section. That's why we only get a fraction of the posts we're supposed to get. It's effectively overriding most of our IN list!

I can work around this by prepending to my tax_query an effective no-op using some custom taxonomy, but this seems like a problem that should be addressed in the WP core.

thank you,

Change History (1)

#1 @SergeyBiryukov
12 months ago

  • Component changed from General to Query
Note: See TracTickets for help on using tickets.