Post Pic

How to: Get latest sticky posts

Introduced in WordPress 2.7, stciky posts are an awesome new functionality, but sadly, retrieving and sorting them isn’t easy as you can expect. In this recipe, you’ll learn how to easily retrieve sticky posts.

To achieve this recipe, place the following code just before the loop:

<?php
	$sticky = get_option('sticky_posts');
	rsort( $sticky );
	$sticky = array_slice( $sticky, 0, 5);
        query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) );
?>

This code will retrieve the 5 most recent sticky posts. To change the number of retrieved posts, just change the 5 by the desired value on line 4.

Credits goes to Justin Tadlock for this awesome recipe!

19 Responses

Apr 11 2009 11:19

Hai, I want to know whether there is a plugin for wp or not for post rotation, but not based on time of post, it must be based on categories. I mean, I have a magazine theme that contains of a lot of categories in frontpage. And I want to keep the post under all categories rotate so that the visitor will see the fresh content. Do you ever hear about that plugin?

thanks before and regards,
hana

Apr 17 2009 19:35

How do I get the latest sticky posts out of just ONE category?

Jun 17 2009 00:38

@david Just add a cat paramater.
The same query with ‘cat’ :
query_posts( array( ‘post__in’ => $sticky, ‘caller_get_posts’ => 1, ‘cat’ => $catid ) );

Aug 18 2009 05:04

Thanks Genius, really helpful.

Aug 23 2009 08:53

Yes, we need this for favorite posting that popular on our web, so the posts will be on the first page every time untill we unsticky.

btw thanks, there is many wp tricks here. i read all your posts. very usefull.

Sep 03 2009 21:40

I’m trying to use this sticky concept, for featured posts, within a specific category… the thing is, I’m calling my own loop, outside The Loop.

query(array(‘post__in’ => get_option(’sticky_posts’))); //sorta works
//$featuredWork->query( array( ‘post__in’ => get_option(’sticky_posts’), ‘caller_get_posts’ => 1, ‘cat’ => $category ) );
while($featuredWork->have_posts()) : $featuredWork->the_post();
$wp_query->in_the_loop = true; // This line is added so that the_tags(”) will work outside the regular loop.
?>

Nov 16 2009 18:51

Thanks friend, i like it

Nov 16 2009 18:56

Very intresting, visit my blog and leave your coment OK.

Jan 29 2010 15:49

I use wp-sticky for stick posts, new versions of wp have some function to stick posts, but plugin solutions is better in my opinion,

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required