Today we will learn how to make wordpress post page Next and Previous Posts With Thumbnails Preview.
Recently One of my client want to create Previous and Next post card. i can be done by following code
Default Previous and Next nav code is
$prevPost = get_previous_post(true); $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
<div id="post-nav"> <?php $prevPost = get_previous_post(true); if($prevPost) { $args = array( 'posts_per_page' => 1, 'include' => $prevPost->ID ); $prevPost = get_posts($args); foreach ($prevPost as $post) { setup_postdata($post); ?> <div class="post-previous"> <a class="previous" href="<?php the_permalink(); ?>">« Previous Story</a> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a> <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> <small><?php the_date('F j, Y'); ?></small> </div> <?php wp_reset_postdata(); } //end foreach } // end if $nextPost = get_next_post(true); if($nextPost) { $args = array( 'posts_per_page' => 1, 'include' => $nextPost->ID ); $nextPost = get_posts($args); foreach ($nextPost as $post) { setup_postdata($post); ?> <div class="post-next"> <a class="next" href="<?php the_permalink(); ?>">Next Story »</a> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a> <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> <small><?php the_date('F j, Y'); ?></strong> </div> <?php wp_reset_postdata(); } //end foreach } // end if ?> </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
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:
Thank You for the code. I’ve a single for custom post type named “Portfolio” and your code doesn’t work. How can I fix it? Thank you
hello Patrizio,
can you share the code here so I can check for you?
Thanks