next and previous post link in WordPress

How to get the next and previous post link in WordPress

Do you want to place the next and previous post links in a single post? You are in the right place. We will show How to get the next and previous post links in WordPress.

When visitors visit a post at that time, post navigation is the most important factor. They want to know what the next post or previous post is. That’s the increase in post-engagement. We will do it without a plugin. Also, we will show it under the while loop. You can get other post data like the next post data and the next post data. 

How to get the next post data:

Just think about it. You are reading an article and then you feel you want to read the next post. WordPress has inbuilt functions that can be shown next post data.

In the while loop, we can get the next post data using the get_next_post() function.

Example:

$next_post = get_next_post();
echo $next_post->post_title;

How to get previous post data:

Same thing you can show previous post data. In the while loop, we can get the next post data using the get_previous_post() function.

Example:

$prev_post = get_previous_post();
echo $prev_post->post_title;

That’s the way you can get the next/previous post data. We will make an example for you to understand. 

Use this simple post navigation code in your single post under the while loop:

<?php
$next_post = get_next_post();
$prev_post = get_previous_post();
?>
<div class="post-navigation" style="display: flex;">
<?php if(!empty($prev_post)): ?>
<div class="prev" style="margin-right:auto;">
<span>Previous Post</span>
<h5 style="margin-top: 0px"><a href="<?php echo esc_url(get_the_permalink($prev_post->ID)) ?>"><?php echo esc_attr($prev_post->post_title) ?></a></h5>
</div>
<?php endif; ?>
<?php if(!empty($next_post)): ?>
<div class="next">
<span>Next Post</span>
<h5 style="margin-top: 0px"><a href="<?php echo esc_url(get_the_permalink($next_post->ID)) ?>"><?php echo esc_attr($next_post->post_title) ?></a></h5>
</div>
<?php endif; ?>
</div>

You can use this code in an under-while loop. You can update and modify the code. If you want to get post navigation outside while looping. You can use the posts_nav_link() function.  

Conclusion: 

We hope this article will help you. This is the easy way to show the next previous post link. We hope you will know How to get the next and previous post links in WordPress.

If you have any problem with this you can comment below.  You will be ready to help you.

See More:

How to Add Bootstrap 5 Pagination in WordPress without Plugin

How to Display Popular Posts by Views in WordPress Without a Plugin

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *