Reputation: 3635
I'm using the following code to display a 'previous posts' link on my Wordpress blog.
<nav>
<ul>
<li><?php previous_posts_link('Newer Entries »') ?></li>
</ul
</nav>
Problem is, when there ARN'T any previous posts, while the link doesn't display, I still get
<nav>
<ul>
<li><</li>
</ul
</nav>
Printed out. Is there an if() statement I could wrap around it all so it checks if there are any previous posts, and only prints it out if there are?
Upvotes: 8
Views: 13380
Reputation: 139
get_previous_post_link() may return an empty string. That's why we check everything with empty():
<?php if( !empty(get_previous_post_link('%link', '%title →', true)) ) { ?>
...
<?php } ?>
We check to see if the string is not empty, and if not, we execute something between the curly braces.
Upvotes: 0
Reputation: 1819
None of the answers worked for me. I solved it this way:
$next = get_permalink(get_adjacent_post(false,'',false)); //next post url
$prev= get_permalink(get_adjacent_post(false,'',true)); //previous post url
<?php if (get_the_permalink()!=$prev): ?>
<a href='<?php echo $prev ?>'>Previous</a>
<?php endif; ?>
<?php if (get_the_permalink()!=$next): ?>
<a href="<?php echo $next ?>">Next</a>
<?php endif; ?>
Upvotes: 3
Reputation: 558
Just to be clear:
Colin's answer isn't correct in my opinion. get_previous_post is not deprecated, previous_post is.
http://codex.wordpress.org/Function_Reference/get_previous_post http://codex.wordpress.org/Function_Reference/previous_post
For me the use of get_next_post works still fine for me.
if(get_next_post()) { }
if(get_previous_post()) { }
Upvotes: 10
Reputation: 53
for people checking this in 2013, get_previous_post has been depreciated.
http://codex.wordpress.org/Next_and_Previous_Links http://codex.wordpress.org/Function_Reference/previous_post
I used to use this :/
if(get_next_post()) { echo 'next'; }
if(get_previous_post()) { echo 'last'; }
But now I use this :)
if(get_next_posts_link()) { echo 'next'; }
if(get_previous_posts_link()) { echo 'last'; }
Upvotes: 2
Reputation: 724
You can try something like this
<?php
if($link = get_previous_posts_link()) {
echo '<ul><li>'.$link.'</li></ul>';
?>
get_previous_posts_link
returns null (falsy value) if there isn't any previous post.
Upvotes: 19