Skip to content

Instantly share code, notes, and snippets.

@leavlzi
Last active May 31, 2021 16:38
Show Gist options
  • Save leavlzi/52e66c2215dd51354b6956edc1606e70 to your computer and use it in GitHub Desktop.
Save leavlzi/52e66c2215dd51354b6956edc1606e70 to your computer and use it in GitHub Desktop.
Use WordPress default function to get next and previous post title with permalink something like this:
<?php // FOR PREVIOUS POST
$prev_post = get_previous_post();
$id = $prev_post->ID ;
$permalink = get_permalink( $id );
?>
<?php // FOR NEXT POST
$next_post = get_next_post();
$nid = $next_post->ID ;
$permalink = get_permalink($nid);
?>
Then just use this variable in your HTML structure like below:
<div class="next-timeline">
<?php next_post_link( '%link', __( 'Next <span class="meta-nav">&rarr;</span>', 'twentyeleven' ) ); ?>
<h2><a href="<?php echo $permalink; ?>"><?php echo $next_post->post_title; ?></a></h2>
</div>
<div class="previous-timeline">
<?php previous_post_link( '%link', __( '<span class="meta-nav">&larr;</span> Previous', 'twentyeleven' ) ); ?>
<h2><a href="<?php echo $permalink; ?>"><?php echo $prev_post->post_title; ?></a></h2>
</div>
@EssiemLtd
Copy link

EssiemLtd commented Jan 3, 2020

Thanks, great snippet.
Here is my slight alteration:

<?php
    $prev_post = get_previous_post();
    $prev_id = $prev_post->ID;
    $prev_permalink = get_permalink($prev_id);
    $next_post = get_next_post();
    $next_id = $next_post->ID;
    $next_permalink = get_permalink($next_id);
    ?>
    <aside class="container">
        <nav class="row">
            <div class="col-6 text-left">
                <div class="previous-timeline">
                    <a href="<?php echo $prev_permalink; ?>" rel="prev">
                        <span class="meta-nav"></span> Previous
                        <h5><?php echo $prev_post->post_title; ?></h5>
                    </a>
                </div>
            </div>
            <div class="col-6 text-right">
                <div class="next-timeline">
                    <a href="<?php echo $next_permalink; ?>">
                        Next <span class="meta-nav"></span>
                        <h5><?php echo $next_post->post_title; ?></h5>
                    </a>
                </div>
            </div>

        </nav>
    </aside>

Updated the variables for consistancy
Wrapped the Next and Title in a single

@Kim-Thu
Copy link

Kim-Thu commented May 31, 2021

THANK YOU, GREAT CODE FOR ME

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment