Conditional Tag for Post/Page Navigation Links in WordPress

170

Have you ever visited a site where they have the styling for post navigation links, but there are no links there? It looks quite ugly and it is distracting for the user. Well if you are a theme designer, or a site owner that is having this issue then this solution is just for you. In this article we are going to share how you can add a conditional tag for post/page navigation links to ensure the best styling for your blog design.

First open your theme’s functions.php file and add the following code:

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

Then place the following code where you want the navigation to be:

<?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; ?>

You don’t have to follow our styling at all. You can modify this code any way you like. The important part is that you keep the navigation styling in between this function:

<?php if (show_posts_nav()) : ?>

<?php endif; ?>

This function will check to see if there is more than one page. If there are more than one page, then it will show the navigation post with the styling. If there are no other pages, then it will not show the styling or the navigation.

Note: the WordPress navigation function is smart enough to not show navigation on it’s own if there are no other pages. But if you have navigation wrapped around with your own custom styling, then those styling code still shows whether navigation is there or not. The function in this post take care of this problem.

Additional Resources:

Eric Martin’s Post – Source for this snippet

Digging into WordPress (A Great eBook that everyone should buy if you are learning WordPress)