Conditional page/post navigation links in WordPress (redux)

November 19th, 2007

After more helpful input, I’ve decided to update my original solution.

Instead of overriding four WordPress functions and adding two new ones in my functions.php file, I have slimmed it down to just one:

/**
 * If more than one page exists, return TRUE.
 */
function show_posts_nav() {
	global $wp_query;
	return ($wp_query->max_num_pages > 1) ? TRUE : FALSE;
}

This function will tell me if there is more than one page…and if there is, I will show the posts navigation (next_posts_link and previous_posts_link). I updated my WordPress (index.php, archives.php and search.php) files with:

<?php if (show_posts_nav()) : ?>
<div class='navigation'>
	<span class='older'><?php next_posts_link('&laquo; Older Entries'); ?></span>
	<span class='newer'><?php previous_posts_link('Newer Entries &raquo;'); ?></span>
</div>
<?php endif; ?>

As for the single post next/previous links, I decided to remove the check because I’ll always have more than one entry.

Much cleaner and less code ;)

Tags: , ,

4 Responses to “Conditional page/post navigation links in WordPress (redux)”

  1. Olaf

    Hi Eric,
    I come from the JQuery-List to you to read about your fine Modal. And what i see here, this fine solution for a long problem with WP. I’m verry happy, thank you.

  2. Author Comment

    Eric Martin

    @Olaf - Thanks, I’m glad it is useful for you. I was surprised that this functionality wasn’t built in to WordPress; maybe it will be in a future version.

  3. jive

    Thanks, I was trying to do this myself just now and noticed they use echo() on those functions so I couldn’t test them with empty().

    :)

  4. Andris

    Thanks for this idea for sharing!
    Now I have built it into my theme that I’m building for release and it is super!
    No empty divs from now!
    Thanks a lot!
    Andris

Leave a Reply

If you'd like to post code in your comment, please wrap your code with a pre and code tag. For example, <pre><code>CODE</code></pre>. Additionally, you'll need to escape the HTML entities (try Postable), otherwise the code will not display properly.