PHP get the first post separately from array returned by wpdb->get_results()

Apologies if the title isn’t clear, can’t quite think how to word this.

I’m getting a pretty standard list of posts like this:

Read More
    $pageposts=$wpdb->get_results("
            SELECT * FROM $wpdb->posts 
            WHERE post_type='post' AND post_status='publish' 
            ORDER BY post_date DESC LIMIT 6
        ", OBJECT);
    $firstpost = array_shift($pageposts);  

But this isn’t returning what I expect. Instead of $firstpost conatining the first post in the array $pageposts (like the docs say it should), it contains the oldest – and $pageposts still also contains that post (which it shouldn’t according to the docs), however the latest post is missing. I don’t know what the Gordon Bennet is going on with this, I’ve also tried array_pop() which should do the opposite of array_shift(), but with similarly strange results (latest post shown but $firstpost still contains the wrong value).

OK I’ve waffled on a bit, so to conclude, here’s what I’m trying to do:
I want to make a single query, get the result, and print out the latest post in one area of the page and then the rest of the posts in another area. Trouble is, in the HTML, the older posts come before the one new post, so I need to split it into a separate variable and make sure the older posts don’t show this new one with the others.

Does this make sense?

Any help appreciated 🙂

Related posts

Leave a Reply

1 comment

  1. once you have set of result in particular order you can achieve it simply as below : –

    $pageposts=$wpdb->get_results("
                SELECT * FROM $wpdb->posts 
                WHERE post_type='post' AND post_status='publish' 
                ORDER BY post_date DESC LIMIT 6
            ", OBJECT);
    

    First time

    $i=1;
    foreach($pageposts as $pageposts_first){
    //here goes your first post
    if($i==1) break;
    }
    

    For rest of posts

    $i=0;
    foreach($pageposts as $pageposts_rest){
     $i++;
       if($i==1) continue;
      //here goes you rest of posts
    }
    

    You can do same thing even if you use get_posts instead..