Hi!
You could check if the posts exists. I know the two functions get_next_post()
and get_previous_post()
check for that.
I know in the core themes they did something similar for some time.
// 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;
}
That’s taken from Twenty Fourteen ( https://core.trac.wordpress.org/browser/tags/4.6/src/wp-content/themes/twentyfourteen/inc/template-tags.php#L74 )
Hi Jose, thanks for this. I inserted this code onto my page inside <?php…?> tags but that didn’t output anything.
I need it to be something like:
IF LATEST POST AMONGST SIBLINGS {
<?php echo get_permalink(get_adjacent_post(false,'',false)); ?>
}
and
IF OLDEST POST AMONGST SIBLINGS {
<?php echo get_permalink(get_adjacent_post(false,'',true)); ?>
}
At the moment they display even if they are the latest/oldest post, and instead of only going to siblings, they go to any page.
Thanks in advance
Is there a reason why you’re not using the_post_navigation() (or previous_post_link() and next_post_link()
These function all don’t show the next or previous post if it doesn’t exist. Or do you find these functions also displaying links it there is no previous/next post?
The post ID is optional for get_permalink()
. If get_adjacent_post()
doesn’t find a post it returns an empty string. That’s why you’ll need to test if a next/previous post was found before passing it to get_permalink()
<?php
$next = get_adjacent_post( false, '', false );
if ( $next ) {
echo get_permalink( $next );
}
$previous = get_adjacent_post( false, '', true );
if ( $previous ) {
echo get_permalink( $previous );
}
?>
Actually, I didn’t know next_post_link/previous_post_link exists! Is it possible to only get the URL though? I ask because they need to sit inside an anchor.
Like next_post_link_url…
Your get_adjacent_post solution works though! 🙂
Thanks keesiemeijer!
Those functions also use get_adjacent_post()
to get the next and previous post urls so I think you’re better of using it directly with the code above.