WordPress – get_posts – Show Sticky Posts First

WordPressWordPress has a feature called “Sticky Posts” (it’s under the “Visibility” section for WordPress posts). As the name implies, the post will be pinned to the front page if checked.

Unfortunately, get_posts seems to ignore this … and will show (by default) in Chronological Order…Which is fine usually. That’s how news should be.

There are other ways to go about this. Using WP_Query for example. But what if you are pretty darn happy with your get_posts and don’t want to change your (possibly) complicated, already-implemented, get_posts variation?

The solution is pretty simple. It isn’t elegant, but it works (for my needs, anyway). If you are starting from scratch, then I would go the wp_query route.

In my example, I want 6 total posts for the front page from a specific category.

Anyway, you basically run two get_posts (redundant, yep). One grabs sticky posts specifically. The other one grabs all posts that are NOT sticky posts. You then combine the two using PHP’s array_merge (making sure sticky posts is the parent that is absorbing the non-sticky array), then you shed off the extras (if they exist) using array_slice.

Here’s what the beginning of the loop would look like.

$args = array( 'category' => 17, 'numberposts' => 6, 'order'=> 'DES', 'orderby' => 'date', 'include' => implode(',', get_option('sticky_posts')) );
$args2 = array( 'post__not_in'=>get_option('sticky_posts'), 'category' => 17, 'numberposts' => 6, 'order'=> 'DES', 'orderby' => 'date' );

$postslist = get_posts( $args );
$postslist2 = get_posts( $args2 );

$postslist = array_merge($postslist, $postslist2);

$postslist= array_slice($postslist, 0, 6);

foreach ($postslist as $post) :  setup_postdata($post); ?>

Boom. Sticky posts added.

Incoming search terms:

  • wordpress get_posts
  • https://yandex ru/clck/jsredir?from=yandex ru;search;web;;&text=&etext=1831 oTV4gN2XMIBaYLCau2Fw96kFeikSoMMKD8_AB5TYRaSftoKzZhR_fdNGikPn23-h 6a76dcdc6b1210a071309283e1dd5efdd2999b4c&uuid=&state=_BLhILn4SxNIvvL0W45KSic66uCIg23qh8iRG98qeIXme
  • https://yandex ru/clck/jsredir?from=yandex ru;search;web;;&text=&etext=1832 Bk92dG6bTY-7UWBhllg4FYCsVK98PlWajkSoi1OvRt0XirzDVvldkYF-39MnoQLZ f1a7591877eb3d75732287bceaef02c027b36e0a&uuid=&state=_BLhILn4SxNIvvL0W45KSic66uCIg23qh8iRG98qeIXme
  • https://yandex ru/clck/jsredir?from=yandex ru;search;web;;&text=&etext=1837 GBawiB6qvbrfrHcBSRT5v43rHtpU-e-XZgjQYcfVtnS3NQ2Va4SiGGXRPscEzq4U 46545331b783bd088bffc90b021d66460e903267&uuid=&state=_BLhILn4SxNIvvL0W45KSic66uCIg23qh8iRG98qeIXme

Leave a Reply

Your email address will not be published.