0

On my website I have a "Breaking News" section which shows the most recent 4 stories in the "Breaking News" Category.

Under this I have a featured news section which displays 5 more stories from the "Breaking News" Category. I get these posts by simply setting the offset to 4 in a WP_Query

What I want to do is make an adjustment to the featured news section. So that it still pulls in 5 of the latest stories from Breaking News, but if a story is added to a "Featured News" category, that it pulls that in.

Some pseduo code would be something like

Get the 5 latest posts from Breaking News with Offset of 4 and from Featured News with Offset 0

Seems pretty simple when it's written like that, but I can't seem to actually get it to work. I can't get WP_Query to accept an offset from one category and not the other.

I've tried this

$featuredPosts = new WP_Query( array(
'posts_per_page' => 5,
'cat' => 169,
'offset' => 4
), 
array(
'posts_per_page' => 5,
'cat' => 172,
'offset' => 0) );

But this only gives me the first 5 posts from cat 169 and ignores the second query array from 172.

I have also tried storing all the id's of posts already outputted in "Breaking News" and then not outputting them again so I can do an easier query (Get last 5 from breaking&featured) but the problem there is it won't always output 5 posts since it will be excluding some of the breaking news ones.

Maybe I'm completely over thinking this and there's an easier way, has anyone any ideas?

3
  • Why not two queries?
    – s_ha_dum
    Mar 29, 2014 at 14:27
  • but how would that work? Yes I could query for posts from Breaking News with offset, then Query for posts from Featured, but how can I combine these into one new object and just get the most recent 5?
    – robobobobo
    Mar 29, 2014 at 14:53
  • Well, you need (or think you need) to query by two different offsets. You can't do that. It doesn't even make sense. Your options are 1) two queries or 2) a very complicated UNION, for example.
    – s_ha_dum
    Mar 30, 2014 at 15:49

1 Answer 1

0

I had a similar problem with a featured section and ended up doing it like this

Fist create your array variable outside the loop:

$exclude_us = array()

Then add the ID of each post in the first loop into the array (in the first loop):

if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
    $exclude_us[] = get_the_id
    ...the rest of the loop...

And then in your second loop, if a post has that ID, skip it (continue):

if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
    if ( in_array ( get_the_id(), $exclude_us ) ) {
        continue;
        }
    ...the rest of the loop...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.