Creating a WordPress Theme — Part 2
Today, we will be looking at using multiple loops in our WordPress theme to separate featured (sticky) posts from regular posts on the home page of the site.
If you've ever worked on a WordPress theme before, you should be familiar with the loop. If you want a detailed explanation, check out the WordPress Codex. Basically, it's what's used to get all our posts and display them on the page.
It usually looks a bit like this:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> Show the posts. <?php endwhile; else: ?> If no posts were found, show this. <?php endif; ?>
We will make use of the following loop for both our "Featured Post" and "Latest Post" loops.
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h3><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3> <?php the_excerpt(); ?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> <pre> This displays the current post's title, with an excerpt. Add this loop into the "Featured Post" box, and the "Lastes Posts" boxes. However, we don't want to show every post in both boxes. To show only a featured post, add this code just before the "Featured Post" loop: <pre lang="PHP"> <?php $sticky = get_option('sticky_posts'); rsort( $sticky ); $sticky = array_slice($sticky, 0, 1); query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); ?>
This is a slightly modified version of this little snippet, to only show one post marked as sticky.
But, you'll notice that the "Latest Posts" box also shows the sticky post. We will fix this by using
query_posts once again.
Add the following line just before the "Latest Posts" loop.
<?php query_posts('caller_get_posts=1&showposts=3'); ?>
This resets the loop to the normal settings, and sets it to only show three posts in this loop.
Be sure to stick around and watch out for the next part of this sub-series, and as always, if you have any questions, don't hesitate to leave a comment!