Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
WordPress Plugins
View all Guides

Conditional Tag for Post/Page Navigation Links in WordPress

Last updated on by
Special WordPress Hosting offer for WPBeginner Readers
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>
<?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)

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.