Family Encyclopedia >> Electronics

How to display the latest sticky posts in WordPress

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 appears on top of your new posts, but only if your theme allows it. In this tutorial, we will show you how to display the latest sticky posts in WordPress.

How to display the latest sticky posts in WordPress

Note:This is an intermediate level tutorial and requires basic HTML/CSS knowledge + knowledge of WordPress themes.

Video Walkthrough

Subscribe to WPBeginner

If you don't like the video or need more instructions, continue reading.

The first thing you need to do is copy and paste this code snippet into your theme's functions.php file or a site-specific plugin.

 function wpb_latest_sticky () / * Obtener todas las publicaciones adhesivas * / $ sticky = get_option ('sticky_posts'); / * Ordena los stickies con los más nuevos en la parte superior * / rsort ($ sticky); / * Obtenga los 5 stickies más nuevos (cambie 5 por un número diferente) * / $ sticky = array_slice ($ sticky, 0, 5); / * Consultar publicaciones adhesivas * / $ the_query = new WP_Query (array ('post__in' => $ sticky, 'ignore_sticky_posts' => 1)); // The Loop if ($ the_query-> have_posts ()) $ return. = '
    '; while ($ the_query-> have_posts ()) $ the_query-> the_post (); $ return. = '
  • '. get_the_title (). '
    '. get_the_excerpt (). '
  • '; $ return. = '
'; else // no se encontraron publicaciones / * Restaurar datos de publicación originales * / wp_reset_postdata (); return $ return; add_shortcode ('latest_stickies', 'wpb_latest_sticky');

The above code queries the WordPress database to retrieve the last 5 sticky posts. It then displays the title of each pinned post with a link in a list format. We've wrapped all of that in a function and created a shortcode.

Now to display your latest sticky posts, you can use the [latest_stickies] shortcode on any WordPress post, page, or even a text widget.

If you want to use shortcodes inside a text widget, you'll need to add this additional line of code in your theme's functions file or site-specific plugin.

 add_filter ('widget_text', 'do_shortcode'); 

This snippet and feature can be used very well in the featured slider or any other advanced features you would like to display on your site. This snippet is primarily geared towards a WordPress site that has a custom homepage or magazine style.

That's it, we hope this article helped you display the latest sticky posts on your WordPress blog. You can also check out our tutorial on how to add an expiration date to sticky posts in WordPress.

If you enjoyed this article, please subscribe to our WordPress YouTube Channel video tutorials. You can also find us on Twitter and Google.+.