WordPress has this very cool feature called sticky posts. Think of sticky posts as featured posts for your blog. When you mark a post as sticky, it shows up above your new posts, but only if your theme permits it. In this tutorial we will show you how to display the latest sticky posts in WordPress.
Note: This is an intermediate level tutorial and requires basic HTML / CSS knowledge + WordPress themes knowledge.
First thing you need to do is copy and paste this code snippet in your themeβs functions.php file or in a site-specific plugin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | function wpb_latest_sticky() { /* Get all sticky posts */ $sticky = get_option( 'sticky_posts' ); /* Sort the stickies with the newest ones at the top */ rsort( $sticky ); /* Get the 5 newest stickies (change 5 for a different number) */ $sticky = array_slice ( $sticky , 0, 5 ); /* Query sticky posts */ $the_query = new WP_Query( array ( 'post__in' => $sticky , 'ignore_sticky_posts' => 1 ) ); // The Loop if ( $the_query ->have_posts() ) { $return .= '<ul>' ; while ( $the_query ->have_posts() ) { $the_query ->the_post(); $return .= '<li><a href="' .get_permalink(). '" title="' . get_the_title() . '">' . get_the_title() . '</a><br />' . get_the_excerpt(). '</li>' ; } $return .= '</ul>' ; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); return $return ; } add_shortcode( 'latest_stickies' , 'wpb_latest_sticky' ); |
The code above queries the WordPress database to retrieve the 5 latest sticky posts. It then displays each sticky postβs title with a link in a list format. We have wrapped all that in a function and created a shortcode.
Now to display your latest sticky posts, you can use the shortcode [latest_stickies] in any WordPress post, page, or even a text widget.
If you would like to use shortcodes inside a text widget, then you will need to add this extra line of code in your themeβs functions.php or site-specific plugin.
This snippet and function can very well be used in featured slider, or any other advanced feature that you would like to display on your site. This snippet is mostly geared toward a WordPress site that has a custom homepage or a magazine style look.
Thatβs all, we hope this article helped you display latest sticky posts on your WordPress blog. You may also want to checkout our tutorial on how to add an expiration date to sticky posts in WordPress.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Google+.