3

I wrote a WP_query and the behaviour is weird. I tried almost everything but that's not working. I found a solution but i try to understand.

The following queries always returns posts from the first caregory (id : 15, slug : slug1).

$args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category__in' => array(15, 17), 'posts_per_page' => 4 ); $query = new WP_Query($args); $items = $query->get_posts(); 

OR

$args = array( 'post_type' => 'post', 'post_status' => 'publish', 'cat' => '15,17', 'posts_per_page' => 4, ); $query = new WP_Query($args); $items = $query->get_posts(); 

OR

$args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category_name' => 'slug1,slug2', 'posts_per_page' => 4, ); $query = new WP_Query($args); $items = $query->get_posts(); 

OR

$args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 4, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array(15,17), ), ), ); $query = new WP_Query($args); $items = $query->get_posts(); 

The solution was to use query_post($args) instead of WP_query->get_posts()

$args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category__in' => array(15, 17), 'posts_per_page' => 4 ); $items = get_posts($args); 

Can you tell me where i'm wrong ?

3
  • 1
    get_posts uses WP_Query but does not apply query filters by default. If you are getting different results from each, you have a query filter which is not correctly targeted. Commented May 11, 2017 at 15:42
  • I do not have any filters (maybe in plugins), but you told me what I want. Commented May 15, 2017 at 9:07
  • 1
    I have this identical issue and it occurs on a vanilla 4.9.8 too. Tested with two categories, it occurred 100% of the times if the categories are on different branches or if a child is supplied before its parent in the array. The result was as expected only when I supplied the array as (<parent>,<child>). There is clearly some kind of bug. Commented Oct 31, 2018 at 14:57

1 Answer 1

5

Following Milo's answer, I found another workaround that works and i'm more confortable with it.

$args = array( 'post_type' => 'post', 'post_status' => 'publish', 'category__in' => array(15, 17), 'posts_per_page' => 4 ); $query = new WP_Query(); $items = $query->query($args); 
2
  • How you fix that? I have same problem... Commented Sep 19, 2018 at 22:26
  • I fixed by using $query = new WP_Query(); $items = $query->query($args); instead of $items = get_posts($args); Commented Sep 27, 2018 at 14:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.