Get Adjacent Posts to Currently Viewed Post

Written by on April 15, 2011 in WordPress Tutorials - 1 Comment

There is a very useful function in WordPress called get_adjacent_posts() that allows us to retrieve either the previous post, or the next post, and all of it’s information, which is stored in a variable. This function is particularly useful for situations, such as portfolios, where you want to display a teaser of the previous or next post, such as the posts’ thumbnails. You can see this exact effect being used on the beautiful Practica Portfolio Theme from Theme Forest.

How It Works

The function looks like this:

1
<?php get_adjacent_post( $in_same_cat, $excluded_categories, $previous ) ?>

$in_same_cat -true/false – whether to retrieve adjacent post from same category. Default: false
$excluded_categories – string of category IDs to exclude. Default: ” (none)
$previous – true/false – whether to retrieve previous (true) or next (false). Default: true

So let’s say that we want to get the previous post and the next post and store each of their post’s data in a set of variables.

1
2
$prev = get_adjacent_post(true,'',true); 
$next = get_adjacent_post(true,'',false);

Then we can display information the prev/next post information like this:

1
2
3
4
5
6
7
8
// display content
echo $prev->post_content;
 
//display title
echo $prev->post_title;
 
//display post thumbnail size 68x68
echo get_the_post_thumbnail($prev->ID, array(68,68, true) );

And you can do exactly the same with the $next post.

To see exactly how this was used in the above mentioned theme, Practica, take a look at a single portfolio image, such as Tribe of Circle and notice the two small thumbnails with the prev / next arrows.

It’s a really cool effect and I highly recommend utilizing it.

Enjoy!

About

Pippin Williamson is an expert WordPress dev with 4+ years of experience. You may follow him on Twitter @pippinspages and @pippinsplugins and see his free WP plugins, themes, and tutorials he has to offer at Pippin's Pages.com and Pippin's Plugins.com

Post comment as twitter logo facebook logo
Sort: Newest | Oldest

Nice hack for WordPress.

It's going to be very useful vor every portfolio theme, and for every blog with a series of article with the same topic.