How to Display the Latest Sticky Posts in WordPress

Sharing is caring!

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.

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.

01 function wpb_latest_sticky() {
02
03 /* Get all sticky posts */
04 $sticky = get_option( ‘sticky_posts’ );
05
06 /* Sort the stickies with the newest ones at the top.
07 * Remove this if you want to display oldest posts first
08 */
09 rsort( $sticky );
10
11 /* Get the 5 newest stickies (change 5 for a different number) */
12 $sticky = array_slice( $sticky, 0, 5 );
13
14 /* Query sticky posts */
15 $the_query = new WP_Query( array( ‘post__in’ => $sticky, ‘caller_get_posts’ => 1 ) );
16
17
18 // The Loop
19 if ( $the_query->have_posts() ) {
20 $return .= ‘<ul>’;
21 while ( $the_query->have_posts() ) {
22 $the_query->the_post();
23 $return .= ‘<li><a href=”‘ .get_permalink($post->ID). ‘” title=”‘ . get_the_title() . ‘”>’ . get_the_title() . ‘</a></li>’;
24
25 }
26 $return .= ‘</ul>’;
27
28 } else {
29 // no posts found
30 }
31
32
33 /* Restore original Post Data */
34 wp_reset_postdata();
35
36 return $return;
37
38 }
39 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.

add_filter('widget_text', 'do_shortcode');

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.

Source: http://www.wpbeginner.com/wp-tutorials/how-to-display-the-latest-sticky-posts-in-wordpress/

Leave a Reply

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

Got Project on mind? Let's ConnectContact Us

Secured By miniOrange