Display a Sticky Post in the Sidebar

Posted on January 22nd, 2011

Here is a simple code that displays a “sticky” post in the sidebar of your theme:

<?php 
// initialize new query of one post from category 11
$my_query = new WP_Query('cat=11&showposts=1');
 
// loop through the database to find related information
while ($my_query->have_posts()) : $my_query->the_post();
 
// set expiration time of two days
$goAwayDate = time() - (60 * 60 * 24 * 2);
 
// get date of sticky post
$postDate = get_the_time('U');
 
// if post is too old, do nothing
if ($postDate < $goAwayDate) {
 
// else show the post
} else { ?>
 
        <h1><?php the_title(); ?></h1>
        <?php the_excerpt(); ?>
 
<?php } endwhile; ?>

This method employs a second loop to display the sticky post, so it may be placed anywhere in your theme’s template files. You can also change the number of days, which the post will remain sticky by editing the expiration variable with a number other than "2". For example, to set a duration period of seven days, you would use this:

$goAwayDate = time() - (60 * 60 * 24 * 7);