Checking if next post exists in WordPress

03 April, 2014 by Tom Elliott

At the end of each of my WordPress articles, I have next post and previous post links that look a little bit like this:

Next post: post title and link
Last post: post title and link

The problem was that on the latest post, the next post doesn’t exist, leaving the ‘Next post’ text on it’s own. The seemingly straightforward task of checking if the next post exists or not escaped me for a bit, and Google results turned up empty (or at least gave unusually long code solutions).

The fix I used to check if a next WordPress post exists was to use the code below:

<?php if (strlen(get_next_post()->post_title) > 0) { ?>
    Next Post: <?php next_post_link( '%link', '%title &raquo;' ) ?>
<?php } ?>

The code simply checks to see if the length of post title of the next post is greater than zero and if it does, displays the next post link. This uses the ‘get_next_post’ function, the contents of which can be seen by using

<?php print_r(get_next_post()); ?>

A similar bit of code can also be used to check if the previous post exists, useful only for the oldest post.

<?php if (strlen(get_previous_post()->post_title) > 0) { ?>
    Last post: <?php previous_post_link( '%link', '%title &raquo;' ) ?>
<?php } ?>


Creating a manual list of related posts in WordPress »


3 Comments

  • Ashe says:

    Very helpful, thanks! 🙂

  • Jennette says:

    Thanks! That helped a lot.

  • Khalid says:

    Thanks TOM ELLIOT, Great tutorial.if i try to debug this code<div class=”syntaxhighlighter php”><?php print_r(strlen(next_post_link()->post_title)); ?></div> i get an notice that say: Notice: Trying to get property of non-object in….So i try to use empty() function and it’s work fine.So my Code look like this:
    <div class=”syntaxhighlighter php”><nav aria-label=”Page navigation” class=”single-post-nav”> <ul class=”pager”> <?php if (!empty( get_previous_post() )) : ?> <li class=”previous”> <?php previous_post_link(‘%link’); ?> </li> <?php endif; ?> <?php if (!empty( get_next_post() )) : ?> <li class=”next”> <?php next_post_link(‘%link’); ?> </li> <?php endif; ?> </ul> </nav></div>

  • Leave a Reply

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

    css.php