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

LVL 7
Brian MatisProduct ManagerAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

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

if (get_previous_post()){
// do true
}else{
//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.
0
 
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.
0
 
eemitCommented:
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 ) {
		return;
	}

...

Open in new window

0
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.
0
 
James RodgersWeb Applications DeveloperCommented:
no worries, let us know if you need anything else.
0
 
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!
0
 
James RodgersWeb Applications DeveloperCommented:
glad I could help.
0
All Courses

From novice to tech pro — start learning today.