How to add next and previous links to your WordPress site

In this article, we’ll add the next and previous links on a WordPress theme.

First We declare the previous and next variables:

$previous = get_previous_post();
$next = get_next_post();

Then to show them inside the post, add the following snippets to the theme’s single.php file:

<?php if ( get_previous_post() ) {?>
<a href="<?php echo get_the_permalink($previous) ?>">
    <img src="<?php echo get_the_post_thumbnail_url($previous) ?>" alt="">
        <h3> <?php echo get_the_title($previous) ?></h3>
        <p> PREV</p>
<?php }?>
<?php if ( get_next_post() ) {?>
<a href="<?php echo get_the_permalink($next) ?>">
    <img src="<?php echo get_the_post_thumbnail_url($next) ?>" alt="">
        <h3> <?php echo get_the_title($next) ?></h3>
<?php }?>

If you want to further customize the links and maybe even display post name inside the links, follow this excellent guide from HostPapa.

Was this post helpful?

Leave a Comment