1. Code
  2. PHP

Quick Tip: Next and Previous Posts With Thumbnails

Scroll to top
2 min read

Media rich content is engaging content, right? And giving readers an opportunity to browse through posts linearly is one good way to keep them at your site reading longer, right? So why just give them a title? This quick tip will give you the programming you need to include the post thumbnail and the date of the next and previous posts. Styling is left up to you.


Check for the Previous and Next Posts

1
2
$prevPost = get_previous_post(true);
3
$nextPost = get_next_post(true);

These two variables will get the previous and next posts if they exist. Now we can check to see if they exist and use the ID with get_posts() to display any information we want to about each post.


Output the Thumbnails and Other Stuff

1
2
<div id="post-nav">
3
	<?php $prevPost = get_previous_post(true);
4
		if($prevPost) {
5
			$args = array(
6
				'posts_per_page' => 1,
7
				'include' => $prevPost->ID
8
			);
9
			$prevPost = get_posts($args);
10
			foreach ($prevPost as $post) {
11
				setup_postdata($post);
12
	?>
13
		<div class="post-previous">
14
			<a class="previous" href="<?php the_permalink(); ?>">&laquo; Previous Story</a>
15
			<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
16
			<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
17
			<small><?php the_date('F j, Y'); ?></small>
18
		</div>
19
	<?php
20
				wp_reset_postdata();
21
			} //end foreach

22
		} // end if

23
		
24
		$nextPost = get_next_post(true);
25
		if($nextPost) {
26
			$args = array(
27
				'posts_per_page' => 1,
28
				'include' => $nextPost->ID
29
			);
30
			$nextPost = get_posts($args);
31
			foreach ($nextPost as $post) {
32
				setup_postdata($post);
33
	?>
34
		<div class="post-next">
35
			<a class="next" href="<?php the_permalink(); ?>">Next Story &raquo;</a>
36
			<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
37
			<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
38
			<small><?php the_date('F j, Y'); ?></strong>
39
		</div>
40
	<?php
41
				wp_reset_postdata();
42
			} //end foreach

43
		} // end if

44
	?>
45
</div>

This code will go into your single.php template. If the posts exist, we use the ID to get that one post and then create a foreach loop to output the following:

  • A generically labeled "Previous/Next" link
  • The post thumbnail wrapped in a link to the post
  • The title in an h2 and wrapped in a link to the post
  • and the date

Conclusion

Once you have this set up with the styling that you prefer you can do any number of things with the post information. You might have something that looks like this:

Custom Meta BoxCustom Meta BoxCustom Meta Box