Get Adjacent Posts to Currently Viewed Post

in WordPress Tutorials

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:

<?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.

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

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

// 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.


Comments (1)

  • Comment by Daniel Roch
    Daniel Roch

    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.