Show The Latest Sticky Posts In WordPress

[ad_1]

WordPress introduced a very cool feature called sticky posts in version 2.7. Since then you’ve been able to assign some posts to be sticky, a sticky post will make sure that this post appears at the top of the list of posts. If you use your WordPress site as a normal blog and have a list of posts of the homepage of your site, making a post sticky will ensure that this post appears at the top of the post list. So far so good but what about running a query to customize and display latest sticky posts.

Unfortunately, working with sticky posts isn’t easy as you can expect. You cannot simply run a post query and display latest sticky posts as we used to do in WordPress but it’s a little tricky because sticky post IDs are stored in WordPress options table instead of post meta, And this makes this matter little complicated. But WordPress developer Justin Tadlock made it easy for us.

To display your five most recent sticky posts, just paste the following code anywhere in your theme files.

<?php
// show the latest sticky posts in wordpress
$sticky = get_option( 'sticky_posts' );
rsort( $sticky );

$args = array(
	'post__in'  => $sticky,
	'posts_per_page' => 5,
	'ignore_sticky_posts' => 1
);

$sticky_query = new WP_Query( $args );

// the loop
if ( $sticky_query->have_posts() ) :
    while ( $sticky_query->have_posts() ) : $sticky_query->the_post();
        get_template_part( 'content', get_post_format() );
    endwhile;
else :
    get_template_part( 'content', 'none' );
endif;

wp_reset_postdata();
?>

If you want to display more or less sticky posts, just change the value of posts_per_page in sticky post query. In this above example, we are showing 5 sticky posts, you can change it to your desired value.

[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads