[wp-trac] [WordPress Trac] #48047: Querying (non-CPT) posts from more than one (native) category only returning posts from first category

WordPress Trac noreply at wordpress.org
Mon Sep 16 08:23:54 UTC 2019


#48047: Querying (non-CPT) posts from more than one (native) category only
returning posts from first category
-------------------------------+-----------------------------
 Reporter:  lialyn             |      Owner:  (none)
     Type:  defect (bug)       |     Status:  new
 Priority:  normal             |  Milestone:  Awaiting Review
Component:  Posts, Post Types  |    Version:  5.2.3
 Severity:  normal             |   Keywords:
  Focuses:  template           |
-------------------------------+-----------------------------
 I tried selecting posts from two categories using this code:

 {{{
 $wpQuery = new WP_Query([
     'post_type'      => 'post',
     'posts_per_page' => 30,
     'post_status'    => 'publish',
     'category__in'   => [5, 6],
 ]);

 $posts = $wpQuery->get_posts();

 }}}

 This code only returns posts from the first category. I tracked this back
 to the query variables `category_name` and `cat` being set to the first
 queried category in the `get_posts()` method. Code from core, `class-wp-
 query.php`, line 2173:

 {{{
 if ('category' === $queried_taxonomy) {

     $the_cat = get_term_by($queried_items['field'],
 $queried_items['terms'][0], 'category');
     if ($the_cat) {
         $this->set('cat', $the_cat->term_id);
         $this->set('category_name', $the_cat->slug);
     }
     unset($the_cat);
 }
 }}}

 It was the same with any equivalent of the `category__in` option, such as
 using a comma separated list as an argument (`'category_name' =>
 'news,video'`) or writing my own `tax_query`.

 When I access the `posts` property on the query object
 (`$wpQuery->posts`), the correct number of posts is returned. The problem
 only surfaces when `get_posts()` is called.

 The bug persists on the Twenty Ninetheen theme without any plugins
 enabled.

 Why is `category_name`/`cat` even set to the first category term? If there
 is a reason, it would make sense to filter out any "duplicate" category
 query vars present before the SQL query is built, because ''both''
 `category__in` and `category_name`/`cat` don't make sense.

 I'm looking forward to insights on this.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/48047>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list