0

I want to use WP_Query to display 2 posts, the latest from category X, and the latest that is not in category X. Is it possible to create one query that does this, or do I have to query twice? If it's possible, how do I create the one query that gives me the result I want?

This is my arguments array for now:

$args = array(
    'post_type' => 'blog',
    'tax_query' => array(
        array(
            'taxonomy' => 'bloggcat',
            'field' => 'slug',
            'terms' => 'appar',
        )
    ),
    'posts_per_page' => '2',
);

This of course is not what I want, but where do I go from here?

-- Edit --

I managed to find a solution that ends up with one merged query that works for me. I'm not sure this is the best solution so if anyone knows a better way, please contribute.

I this solution, I make two WP_query's with different arguments, then merge them, like so:

$podArgs = array(
    'post_type' => 'blog',
    'tax_query' => array(
        array(
            'taxonomy' => 'bloggcat',
            'field' => 'slug',
            'terms' => 'appar',
        )
    ),
    'posts_per_page' => '1',
);
$notPodArgs = array(
    'post_type' => 'blog',
    'tax_query' => array(
        array(
            'taxonomy' => 'bloggcat',
            'field' => 'slug',
            'terms' => 'appar',
            'operator' => 'NOT IN'
        ),
    ),
    'posts_per_page' => '1',
);

$pods = new WP_Query($podArgs);
$notPods = new WP_Query($notPodArgs);
$blogs = new WP_Query();
$blogs->posts = array_merge( $pods->posts, $notPods->posts );
$blogs->post_count = $pods->post_count + $notPods->post_count;
1

Queries (both WP_Queries and raw SQL queries) are meant to select objects matching given criteria.

"One post from category and one not from category" is not a description of set of posts - it's description of two posts coming from different sets.

This means you won't be able to select these two posts using only one query...

So yes, you'll have to use two queries for that.

| improve this answer | |
  • Yeeaah that makes sense, my lack of query language experience shines through. Anyway I posted a solution that ends up with one merged query, seems to do the trick. – Johan Dahl Jan 25 '19 at 10:12
  • 1
    Not exactly. You're still doing two queries and then only merge the results (merged results of 2 queries is not the same as merged query) – Krzysiek Dróżdż Jan 25 '19 at 10:14
  • Yeah you are right. The main thing for me is that I do not need to repeat my markup for the content. In the end, I just wan't to loop over one array of posts, and that's what I get to do here. – Johan Dahl Jan 25 '19 at 10:18
  • And it should be OK, i guess. – Krzysiek Dróżdż Jan 25 '19 at 10:19

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.