Say you want to use the next_posts_link() and previous_posts_link() functions to display your post navigation. But you want to use some clever lookin’ arrow images(or just plain boring text). You also want the images(or that plain boring text) grayed out when there are no more pages to link to.
Whoa there’s the problem, the next_posts_link() and previous_posts_link() functions don’t output anything when there are no more pages to link to. A little PHP to the rescue.
The Code
The code is pretty easy, just an if else statement. We are going to use the get_next_posts_link() and get_previous_posts_link() to test if there is a link or not.
<?php
// Check for a link to older posts
if ( get_next_posts_link() ) {
// If there is a link to older pages output this code
echo '';
next_posts_link('Previous', '0');
echo '';
} else {
// If there isn't a link output our own code
echo 'no older posts';
};
// Check for a link to newer posts
if ( get_previous_posts_link() ) {
// If there is a link to older pages output this code
echo '';
previous_posts_link('Newer', '0');
echo '';
} else {
// If there isn't a link output our own code
echo 'no newer posts';
};
?>
To break it down a bit, there is an if else block for each link. The if statement checks get_next_posts_link() or get_previous_posts_link(), if it returns a link we call next_posts_link() or previous_posts_link() if it doesn’t we echo our own code.
Something to keep in mind is that normally “next” refers to older posts and “previous” refers to newer posts, which can be confusing while looking at the code.
4 Comments
Leave a CommentHey Curtis I have a blog that don’t have this, no previous or next page for the post, I just got this theme and like it but This is the only thing I don’t like about it, will the code above work and if so can you tell me where to put it?
Thanks in advance… Richard
14th Dec 2008
Hey Curtis, It did work… I can’t believe I got that to work!
The newer and previous text run together but I was able to get them to move over some LOL!
Thanks so much for that code, I’ve learned a good bit from you and I think you very much.
Thanks, Richard
14th Dec 2008
Richard,
Glad you got it to work, if all you wanted was some basic navigation you could probably get away with half of that code though.
There are some examples in the wordpress codex that are simpler.
14th Dec 2008
Hey Curtis,
I’m trying to use SEO pager for wordpress and it says to “comment out next_posts_link and previous_posts_link functions” so that the pager can automatically be placed in the template.
What???…lol. I understand it in theory but the code for the updated WP is complicating things.
Any suggestions? Thanks!
11th Feb 2009