One problem I came across in making the theme “So Fresh So Clean” (to be discussed in a future blog post) was attempting to display a list of my recent blog posts without needing to use a sidebar widget. The theme is influenced by many different web designs, but borrows a few concepts from Dave Shea’s website Mezzoblue. The idea came from the book Building Findable Websites: Web Standards SEO and Beyond. In the section Displaying Your Most Recent Posts, Aaron Walter discusses Dave’s technique for displaying one post on his front page, and a list of the most recent posts in the top section of his website. Dave suggests that in order to do this you can use the following code in the WordPress loop:
<ul id="recent-posts">
<?php $posts = get_posts('numberposts=5&offset=1');
foreach ($posts as $post): ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
While this code does work, it can be problematic, the get_post() query overwrites the WordPress default variables. This means if you run any other loop specific code (i.e. the_title, the_content, the_date, etc.) they will all be affected and many not produce desired results. In my initial testing every page that used The Loop was getting it’s information from the get_posts() query as it overwrites WordPress’ default queries for pages, searches and archives. Thus they all displayed the same information.
After some searching I found a solution for the problem, creating a new WP_Query() object so that it doesn’t interfere with WordPress default functions. Here’s an updated example of the code presented above using this technique.
<ul id="recent-posts">
<?php $recent_posts = new WP_Query(); $recent_posts->Query('showposts=5@offset=1');
while ($recent_posts->have_posts()) : $recent_posts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
If you want something a bit fancier, here’s how I created the recent posts section using the same technique.
<div id="recent_posts">
<h2>Recent Posts</h2>
<?php $recent_posts = new WP_Query(); $recent_posts->Query('showposts=5@offset=1');
while ($recent_posts->have_posts()) : $recent_posts->the_post(); ?>
<div class="recent_date"><?php the_time('m.d.Y') ?></div>
<div class="recent_post_title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<br />
<?php endwhile; ?>
</div>
A deeper discussion in how to do this is on the Weblogs Tools Collection (where I found the solution). The lesson here is, in order to avoid conflicts with WordPress default functions, plugin, and countless other issues, create a new WP_Query(); object.
