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 Answer
1

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);

Leave a Reply

Your email address will not be published. Required fields are marked *