WordPress recent posts getting unpublished posts

From wordpress documentation this is the way to get recent posts

$number_recents_posts = 5;//Can be how many you want
$recent_posts = wp_get_recent_posts( $number_recents_posts );
foreach($recent_posts as $post){
   // if ($post["post_status"]=="publish")
   // ....                   
}

Then one day you might find it out that your unpublished posts sneak into the list of recent posts, if that post link is clicked a ‘Not Found’ page will be displayed.

After some dig around of source code I found that wp_get_recent_posts() function implementation is as following

$sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status IN ( 'draft', 'publish', 'future', 'pending', 'private' ) ORDER BY post_date DESC $limit";
$result = $wpdb->get_results($sql, ARRAY_A);

as you can see it returns the requested number of recent posts in regardless of post status.

You might think adding a conditional check on post_status field will help, but it poses another problem that is the number of recent posts might not be accurate.

Here is my solution

   <?php /*Recent 5 posts*/
                     query_posts('posts_per_page=5');
                    
                    while (have_posts()) : the_post(); 
                    // Do special_cat stuff
                    ?>
                    <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
                    
                    <?php endwhile;?>

As it is bit unusual to loop and get access of particular fields, so a detailed example is given here. It is using the main wp_query, the same query is used to list posts on posts page, and the query results are context aware, like the login status of viewer etc. The implementation is very complex so it is not presented here, but you can find it in query.php.

Hope this helps.

Tags:

This entry was posted on Wednesday, August 4th, 2010 at 2:59 am and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “WordPress recent posts getting unpublished posts”

  1. Thanks, this code works

  2. Hi,

    I am going to try WordPress on my website. I am getting the zip file right now. While getting it i was searching for some info on WordPress. That is how i came acros your blog post. Thanks for the info you shared, i will certanly use it when i am going to use wordpress.

    Will come back here!

  3. Koko says:

    Hi, just had this Problem and could fix it with your help. Thanks alot.

Leave a Reply

*