Get the latest x number of wordpress sticky posts

May 16, 2009 · Print This Article

Some of you may be wanted to know how to query a specific number of sticky posts for the front page.

we’ll assume you already have the loop set up in one of your template files (i.e., home.php, custom-page.php). What we need to do is call up a specific number of stickies.

For this example, we’ll load the two latest sticky posts.

Just place following php code before your loop:

/* Get all sticky posts */
$sticky = get_option( 'sticky_posts' );

/* Sort the stickies with the newest ones at the top */
rsort( $sticky );

/* Get the 2 newest stickies (change 2 for a different number) */
$sticky = array_slice( $sticky, 0, 2 );

/* Query sticky posts */
query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) );

We have to use rsort() to sort the sticky posts in reverse order by post ID (newer posts first). The reason for this is because sticky posts are added to the sticky array according to when they were made sticky, not by ID.

We have to set caller_get_posts to 1. Otherwise, we’d get all stickies added.

Your choice for site templates and wordpress themes


Got something to say?

You must be logged in to post a comment.