Tag Related

WordPress: Display Recent, Related or Random Posts in Your Sidebar

You may have noticed that I have dynamic sidebar that changes slightly as you browse the different parts of the site. For example, I have random posts in my home sidebar, while this changes to related posts when browsing a specific post.

One visitor emailed me recently asking me if I could tell her how I managed to display recent, related or random posts in my sidebar.

Well, I neither use a plugin nor SQL statements for this part.

I used the conditional tags to check the current page and to execute the right part of the code.

The Code in Pieces

I divided the code into three pieces, so you can understand it easily.

Recent Posts


<div class="widget">
<h2>Recent Posts</h2>
<ul>
<?php $posts = get_posts('numberposts=3'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?><br />
<span><?php the_excerpt(); ?><br /><em>&mdash;Posted on <?php the_time('n/j/Y') ?></em></span></a>
</li>
<?php } ?>
</ul>
</div>

The above code picks the latest three posts. You can change the number of posts displayed by changing number in get_posts('numberposts=3'); to whatever you like.

Related Posts by Category


<div class="widget">
<h2>Related Posts</h2>
<ul>
<?php $posts = get_posts('numberposts=3&category='.$category->cat_ID.'&exclude='.$current_post);
foreach($posts as $post) {
?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title() ?>"><?php the_title() ?><br />
<span><?php the_excerpt(); ?><br /><em>&mdash;Posted on <?php the_time('n/j/Y') ?></em></span></a>
</li>
<?php } ?>
</ul>
</div>

We used get_posts('numberposts=3&category='.$category->cat_ID.'&exclude='.$current_post); to make all the business easier. $category->cat_ID pulls the current post’s category, exclude='.$current_post makes sure to exclude the current post from the related ones.

You may use related posts by tag alsoWP Recipes

Random Posts


<div class="widget">
<h2>Random Posts</h2>
<ul>
<?php $posts = get_posts('orderby=rand&numberposts=3'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?><br />
<span><?php the_excerpt(); ?><br /><em>&mdash;Posted on <?php the_time('n/j/Y') ?></em></span></a>
</li>
<?php } ?>
</ul>
</div>

Our code uses orderby=rand. So WordPress will pick 3 random posts from the database every time our site loads.

Final Thoughts

The above codes can be merged together and displayed on the sidebar using the WordPress conditional tags.

If you have enjoyed this post or have any questions or recommendations, please share your views in the comments section.