Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

<?php
            $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
add comment

1 Answer

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().

Regards.

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
var_dump(get_last_published_post());
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
add comment

Your Answer

 
discard

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.