How to get Previous / Next Post Title, Thumbnail and links
This post explains how to get Previous Next Posts titles, thumbnail and url links separately in the single.php page.
This was a little tricky situation when i was working on a new WordPress Theme that needed to display the thumbnail of the previous and next post as well as the post titles and url links. I found some tutorials online which worked, however i noticed that when i get to the last post or first post, the code returned an error like “notice: trying to get property of non-object in”
//Get Previous Post Thumbnail and link $prevPost = get_previous_post(); $prevThumbnail = get_the_post_thumbnail( $prevPost->ID ); previous_post_link( '%link', $prevThumbnail ); //Get The Next Post Thumbnail and link $nextPost = get_next_post(); $nextThumbnail = get_the_post_thumbnail( $nextPost->ID ); next_post_link( '%link', $nextThumbnail );
The above code worked but returned the below error each time the last or first post in the blog is reached. Moreover, it was not exactly what i was looking for.
After thorough practising and searching i finally found the perfect solution which enabled me to get the thumbnail and URL separately.
The code below was perfect for exactly what i was working on, getting the previous post and next post thumbnail url as well as the clickable url and the post titles.
//Get the thumnail url of the previous and next post $prevThumb = get_the_post_thumbnail_url( get_previous_post(), 'thumbnail-size' ); $nextThumb = get_the_post_thumbnail_url( get_next_post(), 'thumbnail-size' ); //Get the links to the Previous and Next Post $previous_link_url = get_permalink( get_previous_post() ); $next_link_url = get_permalink( get_next_post() ); //Get the title of the previous post and next post $prevTitle = get_the_title( get_previous_post() ); $nextTitle = get_the_title( get_next_post() );
The screenshot image is exactly what i was aiming for and the code above worked perfectly for that purpose.
I hope this solves someone else’s problem. Please leave comments below if you have other solutions that works better and want to share.