WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using WP Query & want to only return 1 post in a category.

Either the most recent sticky else the latest post.

Is this possible?

Thanks, George

            $category1 = new WP_Query();
            $category1->query( array('showposts' => 1, 'category_name' => 'hapless  ' ));
            while ($category1->have_posts()) : $category1->the_post(); ?>

                    <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
                    <?php the_post_thumbnail(); ?>  

            <?php endwhile; ?>
share|improve this question
up vote 1 down vote accepted

Why don't you use a fat-free $wpdb->get_var() for the task?

global $wpdb;
$ID = $wpdb->get_var("SELECT `ID` FROM {$wpdb->posts}
    WHERE `post_type`='post' AND `post_status`='publish'
    ORDER BY `post_date_gmt` DESC LIMIT 1;");
$post = $ID ? get_post($ID) : null; // Now get the actual post

This is way more efficient and light-weight. Without all the bells and whistles of the get_posts() or WP_Query().


UPDATE: (more in context)

function get_last_published_post(){
    global $wpdb;
    // Get the ID of the last published post (by date)
    $ID = $wpdb->get_var("SELECT `ID` FROM {$wpdb->posts}
        WHERE `post_type`='post' AND `post_status`='publish'
        ORDER BY `post_date_gmt` DESC LIMIT 1;");
   return $ID ? get_post($ID) : null; // Now get the actual post
// Should print out the Post object
share|improve this answer
Sorry, can't get this to work. Can you give me an example in context please. – George Wiscombe Nov 1 '11 at 9:54
Added an update. – EarnestoDev Nov 1 '11 at 9:58
This is great, is there a way I can use a category in the var_dump? e.g. var_dump(get_last_published_post('category-name')); – George Wiscombe Nov 1 '11 at 13:00
If you need categories and tags and such, it's best to use get_posts(). Returns a WP_Query results in one strike. Same arguments. – EarnestoDev Nov 1 '11 at 21:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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