Free Wordpress Blog Setup

Conditional Tag for Post/Page Navigation Links in WordPress

By Editorial Staff in Themes
Conditional Tag for Post/Page Navigation Links in WordPress

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)

What Next?

Digg it
Save This Page
Subscribe to WPBeginner
Stumble it
Free Wordpress Blog Setup

Share Your Opinions

Tell us what you're thinking...
and if you want a pic to show with your comment, then get gravatar!

Please make sure that you have read our Comment Policy.

Due to high volume of request from our readers, we are adding this feature that allows you to stay updated with this post's comments without having to participate in the discussion even though we would love your input as always. Don't worry we hate SPAM just as much as you do, so you will never receive any SPAM messages from our site and that's our promise to you.

Subscribe without commenting

Close Bar