How to determine if Previous Post or Next Post exist in Wordpress?

In a Wordpress blog, I needed a way for a post to be able to determine if there's either a previous post or a next post that exist before or after it.

I've got a way to do it, but it seems unnecessarily complex and I was just wondering if someone had a more elegant way to accomplish the same thing?

Here's the example of how I'm currently determining if a previous post exists:
if (strlen(get_previous_post()->post_title) > 0)

Open in new window

Brian MatisProduct ManagerAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

James RodgersConnect With a Mentor Web Applications DeveloperCommented:
you can do this instead

if (get_previous_post()){
// do true
//do false

Open in new window

the get_previous_post and get_next_post functions return Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
Brian MatisProduct ManagerAuthor Commented:
Thanks! I'll give this a try when I get a chance, but I seem to recall trying something like this at first and having a problem because the empty string didn't actually evaluate to false.
See how it is done in Twenty Fourteen Theme:

 * Display navigation to next/previous post when applicable.
 * @since Twenty Fourteen 1.0
function twentyfourteen_post_nav() {
	// Don't print empty markup if there's nowhere to navigate.
	$previous = ( is_attachment() ) ? get_post( get_post()->post_parent ) : get_adjacent_post( false, '', true );
	$next     = get_adjacent_post( false, '', false );

	if ( ! $next && ! $previous ) {


Open in new window

Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

Brian MatisProduct ManagerAuthor Commented:
Sorry, still haven't had a chance to go and try this out. Should be able to some evening this week and then I'll report back on how it goes.
James RodgersWeb Applications DeveloperCommented:
no worries, let us know if you need anything else.
Brian MatisProduct ManagerAuthor Commented:
Yep, Jester_48's solution totally worked! I must have done something wrong when I had first tried a similar solution. Now my code is much cleaner. Thanks!
James RodgersWeb Applications DeveloperCommented:
glad I could help.
All Courses

From novice to tech pro — start learning today.