2

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 ?

  • 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. – Milo May 11 '17 at 15:42
  • I do not have any filters (maybe in plugins), but you told me what I want. – Ludovic M. May 15 '17 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. – DrLightman Oct 31 '18 at 14:57
3

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);
| improve this answer | |
  • How you fix that? I have same problem... – bilimokur Sep 19 '18 at 22:26
  • I fixed by using $query = new WP_Query(); $items = $query->query($args); instead of $items = get_posts($args); – Ludovic M. Sep 27 '18 at 14:15

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.