Hiding Wordpress page links

When developing a custom Wordpress theme, it's necessary to provide prev/next navigation wherever there might be more than one page of posts: the main index, search results pages, and archive pages, for example.

posts_nav_link() provides the simplest way to do this—it automatically displays either or both of the links, as needed. If you need more control over the markup, next_posts_link() and previous_posts_link() let you display them independently.

Typical usage goes something like this:

<div class="pager">
    <div class="pager-prev"><?php next_posts_link('&laquo; Older Entries'); ?></div>
    <div class="pager-next"><?php previous_posts_link('Newer Entries &raquo;'); ?></div>
</div>

But there's a problem here. What if a single page of results is being displayed? Wordpress will render an empty pager:

<div class="pager">
    <div class="pager-prev"></div>
    <div class="pager-next"></div>
</div>

In my latest Wordpress theme (the one you're looking at right now), this was throwing off my layout in some browsers. Despite enormous progress in browser standardization, there are still inconsistencies in the way browsers handle empty elements. Some will reserve vertical space for the element; some won't. Some will respect any margins that have been specified for the element; some won't.

Ideally, we simply wouldn't render a pager at all if one isn't needed.

Surprisingly, Wordpress doesn't offer a simple way to determine whether the current query result spans multiple pages. There's is_paged(), but it always returns false for the first page of results, so it won't work.

Fortunately, $wp_query provides the information we need:

if ( $wp_query->found_posts > $wp_query->get('posts_per_page') ) {
    // show pager
}

This seems to work well so far!

Comments

No comments yet.

Leave a Reply

(will not be published)
(optional)

What My Clients Say

Travis Miller's professionalism and experience is an invaluable asset to Airplane Corporation. His technical development skills are on par with the best in the industry. He completes projects on time and on budget, and is truly a pleasure to work with.

—Christian Childs
Airplane Corporation