Introduction
Tired of the standard text-only links for previous and next posts? This guide shows you how to enhance your WordPress single post navigation by adding post thumbnails alongside the titles.
Function Code
Add the following function to your theme's functions.php file. It retrieves a thumbnail for a given post ID, using the featured image first, then the first image from the post content, and finally a random default image.
// Display thumbnail for previous/next post navigation
function wptoo_pageturn_thumb($id){
if (has_post_thumbnail($id)) {
echo get_the_post_thumbnail($id, 'thumbnail', array('class' => 'prevnext-thumb'));
} else {
$first_img = '';
$post_content = get_post($id)->post_content;
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
if (!empty($matches[1][0])) {
$first_img = $matches[1][0];
}
if (empty($first_img)) {
// Define default image path; adjust for your theme
$random = mt_rand(1, 10);
$first_img = get_stylesheet_directory_uri() . '/images/random/' . $random . '.jpg';
}
echo '<img class="prevnext-thumb" src="' . esc_url($first_img) . '" alt="' . esc_attr(get_the_title($id)) . '" />';
}
}
Implementation
Step 1: Add the Function
Place the function code above into your theme's functions.php file.
Step 2: Add Template Code
Insert the following code into your single.php template file where you want the navigation to appear (e.g., after the post content).
<?php
$current_category = get_the_category();
$prev_post = get_previous_post($current_category, '');
$next_post = get_next_post($current_category, '');
?>
<div class="post-navigation">
<?php if (!empty($prev_post)): ?>
<div class="nav-previous">
<?php wptoo_pageturn_thumb($prev_post->ID); ?>
<a href="<?php echo get_permalink($prev_post->ID); ?>" rel="prev">
<span>Previous: <?php echo esc_html($prev_post->post_title); ?></span>
</a>
</div>
<?php endif; ?>
<?php if (!empty($next_post)): ?>
<div class="nav-next">
<?php wptoo_pageturn_thumb($next_post->ID); ?>
<a href="<?php echo get_permalink($next_post->ID); ?>" rel="next">
<span>Next: <?php echo esc_html($next_post->post_title); ?></span>
</a>
</div>
<?php endif; ?>
</div>
Key Notes
- The function safely escapes URLs and attributes.
- It uses semantic
rel="prev"andrel="next"attributes for links. - CSS classes (
post-navigation,nav-previous,nav-next,prevnext-thumb) are provided for easy styling. - Ensure your theme has a default image directory at
/images/random/containing files named 1.jpg to 10.jpg, or modify the path accordingly.