How to retrieve “sticky” post outside the “loop”?
-
16-10-2019 - |
Question
I need to display the "sticky" post in a section that is outside the "loop".
Can someone tell me how to do this?
Solution
I am using this query;
<?php
$sticky = get_option( 'sticky_posts' ); // Get all sticky posts
rsort( $sticky ); // Sort the stickies, latest first
$sticky = array_slice( $sticky, 0, 1 ); // Number of stickies to show
query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); // The query
if (have_posts() ) { while ( have_posts() ) : the_post(); ?>
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php endwhile;?>
<?php } else { echo ""; }?>
Hope it works for you too.. :)
OTHER TIPS
$last_sticky_post = get_post(end(get_option('sticky_posts')));
if(!empty($last_sticky_post)):
setup_postdata($last_sticky_post);
the_title(); // standard loop here...
the_content();
endif;
(this gets a single post)
use get_posts() with the 'include' => implode(',', get_option('sticky_posts'))
argument to get all sticky posts (Martin's solution without array_slice will do the same).
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange