Get the latest sticky posts in WordPress

I came across an interesting question the other day. A user wanted to know how to query a specific number of sticky posts for the front page. Generally, I just point people to the Definitive Sticky Posts Guide for WordPress, but this question was not covered.

The problem:

  • User has many sticky posts (maybe 100s).
  • User wants to only show a specific number of those ordered by date.

Some of you may be thinking that this should be extremely simple. But, let me warn you, I thought the same thing at first. I had to actually put on the ol’ thinking cap for this one.

Get the latest x number of sticky posts

I’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.

Place this 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.

The biggest problem here is that you have to add $sticky[0], $sticky[1], $sticky[2], and so on. But, typing a few extra characters is a small price to pay for the functionality it offers. Updated: Hat tip to Nathan Rice for the array_slice() solution.

Other solutions for sticky-post issues?

As more users start taking advantage of sticky posts, there’ll probably be more issues such as this one pop up. Have you run into any problems querying sticky posts in a certain way? If so, how did you figure it out?

I hope this tutorial at least helps some of you out when working with sticky posts. If you have a more elegant solution for the issue posted above, I’d love to see the code.