WordPress: show sticky posts, then show all other posts in one loop

David Nash php, wordpress 1 Comment

This is something that’s driven me a little insane for a while. WordPress posts can be marked “sticky”, which is awesome.

But if you’re not using it on the home page it just doesn’t work.

In the past I’ve given up and resorted to doing two “The Loop”s, one with just stickies and one without.

But there’s an easier way. In your themes functions.php, do this:

add_filter('the_posts', function ($posts) {
	$stickies = array();

	foreach($posts as $i => $post) {
		if(is_sticky($post->ID)) {
			$stickies[] = $post;
			unset($posts[$i]);
		}
	}
	return array_merge($stickies, $posts);
});

There’s nothing else to chage – the filter just steps in and takes care of it!

Based on this answer http://wordpress.stackexchange.com/a/87788, which I only needed to minimally modify to get working.

This uses PHP anonymous functions, which is supported from version 5.3… and I love, because it reminds me of jquery, and keeps all the code together.

Comments 1

  1. Thank you sooo much for this! Had been racking my brain for a couple hours trying to find a solution and kept coming across outdated/broken solutions and plugins.

    Thanks again, much appreciated!!! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *