Display sticky post and exclude it from recent posts list in WordPress
We were working on a WordPress site that needed to display a sticky post at the top of the blog page with one style, and then below it a list of the most recent posts with a completely different style.
I realize that you can just style the sticky post using the sticky-related classes provided by WordPress:
<div <?php post_class(); ?>> and .sticky class
but I needed to have design elements appear in between the sticky post and the rest of the recent posts, and the recent posts needed to have a completely different design than the sticky. Therefore I decided to go with a 2 loop solution. Once we were using two loops, we had to also make sure that sticky post did not repeat itself and appear in the list of recent posts following it.
Nathan Rice provides a lot of useful information about sticky posts but I couldn’t get the code he posted to work properly. So I went on a hunt to figure it out.
How to display a sticky post
$sticky = get_option( ‘sticky_posts’ );
query_posts( array( ‘post__in’ => $sticky, ‘caller_get_posts’ => 1, ‘orderby’ => ID, ‘showposts’ => 2 ) );
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a href=”<?php the_permalink(); ?>” rel=”bookmark” title=”Permanent Link to <?php the_title(); ?>”>
<?php endif; ?>
It worked very nicely.
How to exclude sticky posts from a list of recent posts
I then wanted to show a list of 3 recent posts that excluded the post that had been defined as sticky. After many trials and errors with different solutions posted around the web, I finally found one that worked on the WordPress Support Forum.
<?php $sticky = get_option(‘sticky_posts’) ;
$post_to_exclude = $sticky;
<h2><a href=”<?php the_permalink() ?>”><?php the_title(); ?></a> </h2>
<?php while (have_posts()) : the_post(); ?>
So there you have it: a workable way to have a WordPress sticky post with one style, and a list of recent posts excluding the sticky post with a completely different style below the sticky post.
Category: Code Snippets