WordPress 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: