Paginated Navigation Bar

One area of web programming that many of us have frequently run into is the need to show a long list of items (whether database results or whatever) in a nicely formatted, easily navigable way.  Usually making the list user friendly involves creating some sort of paging system which allows the user to view various pages of results.  Unfortunately coding such a beast can quickly get ugly.

The following function will (hopefully) help you to make that process easier.  The function is designed to take a few input parameters such as the total number of results, and how many you want to display per page, and create a simple paged navigation bar for you.

<?php

/**
 * Get a paginated navigation bar
 *
 * This function will create and return the HTML for a paginated navigation bar
 * based on the total number of results passed in $num_results, and the value
 * found in $_GET['pageNumber'].  The programmer simply needs to call this function
 * with the appropriate value in $num_results, and use the value in $_GET['pageNumber']
 * to determine which results should be shown.
 * Creates a list of pages in the form of:
 * 1 .. 5 6 7 .. 50 51 .. 100
 * (in this case, you would be viewing page 6)
 *
 * Code taken from http://www.warkensoft.com/2009/12/paginated-navigation-bar/
 *
 * @global    int        $_GET['pageNumber'] is the current page of results being displayed.
 * @param    int     $num_results is the total number of results to be paged through.
 * @param    int     $num_per_page is the number of results to be shown per page.
 * @param    bool    $show set to true to write output to browser.
 *
 * @return    string    Returns the HTML code to display the nav bar.
 *
 */
function get_paged_nav($num_results, $num_per_page=10, $show=false)
{
 // Set this value to true if you want all pages to be shown,
 // otherwise the page list will be shortened.
 $full_page_list = false; 

 // Get the original URL from the server.
 $url = $_SERVER['REQUEST_URI'];

 // Initialize the output string.
 $output = '';

 // Remove query vars from the original URL.
 if(preg_match('#^([^\?]+)(.*)$#isu', $url, $regs))
 $url = $regs[1];

 // Shorten the get variable.
 $q = $_GET;

 // Determine which page we're on, or set to the first page.
 if(isset($q['pageNumber']) AND is_numeric($q['pageNumber'])) $page = $q['pageNumber'];
 else $page = 1;

 // Determine the total number of pages to be shown.
 $total_pages = ceil($num_results / $num_per_page);

 // Begin to loop through the pages creating the HTML code.
 for($i=1; $i<=$total_pages; $i++)
 {
 // Assign a new page number value to the pageNumber query variable.
 $q['pageNumber'] = $i;

 // Initialize a new array for storage of the query variables.
 $tmp = array();
 foreach($q as $key=>$value)
 $tmp[] = "$key=$value";

 // Create a new query string for the URL of the page to look at.
 $qvars = implode("&amp;", $tmp);

 // Create the new URL for this page.
 $new_url = $url . '?' . $qvars;

 // Determine whether or not we're looking at this page.
 if($i != $page)
 {
 // Determine whether or not the page is worth showing a link for.
 // Allows us to shorten the list of pages.
 if($full_page_list == true
 OR $i == $page-1
 OR $i == $page+1
 OR $i == 1
 OR $i == $total_pages
 OR $i == floor($total_pages/2)
 OR $i == floor($total_pages/2)+1
 )
 {
 $output .= "<a href='$new_url'>$i</a> ";
 }
 else
 $output .= '. ';
 }
 else
 {
 // This is the page we're looking at.
 $output .= "<strong>$i</strong> ";
 }
 }

 // Remove extra dots from the list of pages, allowing it to be shortened.
 $output = ereg_replace('(\. ){2,}', ' .. ', $output);

 // Determine whether to show the HTML, or just return it.
 if($show) echo $output;

 return($output);
}

// Sample usage
$total_results = 100;
$results_per_page = 5;
$html = get_paged_nav($total_results, $results_per_page, false);
echo 'Page: ', $html;

?>

Here is a screenshot of what the output of the function looks like. You can of course format this to look however you want with CSS.

Screenshot of function output

Screenshot of function output

If you find this to be useful you’re welcome to download it.  The code is free to use and if you’re really nice you’ll link back to me or digg it. (see the share and save controls under the post title.

If you have thoughts, comments or suggestions on how to improve it, I’d love to hear them in the comments below.

Related Reading:

Php: Learn PHP In A DAY! - The Ultimate Crash Course to Learning the Basics of PHP In No Time (Learn PHP FAST - The Ultimate Crash Course to Learning ... of the PHP Programming Language In No Time)Php: Learn PHP In A DAY! - The Ultimate Crash Course to Learning the Basics of PHP In No Time (Learn PHP FAST - The Ultimate Crash Course to Learning ... of the PHP Programming Language In No Time)PHP Programming Language Are You Ready to Know All About PHP? Today only, get this Kindle Book for just $8.99. Regularly priced at $11.99. Read on yo... Read More >
Learn PHP: The Complete Beginner’s Guide To Learn PHP Programming (PHP Guide)Learn PHP: The Complete Beginner’s Guide To Learn PHP Programming (PHP Guide)Do you want to learn PHP Programming?
Are you looking for an easy answer to what looks like a complex problem?
PHP programming can be used f... Read More >
Java: 2017 Ultimate Beginners Guide to Learn Java Programming  ( java for dummies, java apps, java for beginners, java apps, hacking, hacking exposed) ... Developers, Coding, CSS, PHP) (Volume 1)Java: 2017 Ultimate Beginners Guide to Learn Java Programming ( java for dummies, java apps, java for beginners, java apps, hacking, hacking exposed) ... Developers, Coding, CSS, PHP) (Volume 1)Java Sale price. You will save 66% with this offer. Please hurry up! 2017 Ultimate Beginners Guide to Learn Java Programming ( java for dummies, jav... Read More >

AmazonFeed v1.9 Released

I’m happy to announce I have completed work on AmazonFeed v. 1.9.  This version includes some very cool features including:

  • Ability to sort the order in which products appear sitewide we well as customizing the sort order on individual posts.
  • Ability to choose where the products appear on the posts/pages, whether below (default) or above the post content.
  • Ability to choose whether or not specific products are displayed in association with individual keywords.  You can block specific products on the cache control page.

Hope you like this new version.  You can download it from WordPress.org.  I’d love to hear your thoughts in the comments area below.

Related Reading:

Amazon FBA: Step-By-Step Guide To Launching Your Private Label Products and Making Money On AmazonAmazon FBA: Step-By-Step Guide To Launching Your Private Label Products and Making Money On AmazonAre You Ready To Quit Your 9-5 Job? Do you want to learn how to make passive income? Have you always wanted your own brand? Are you tired of not bein... Read More >
Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 (Learning Php, Mysql, Javascript, Css & Html5)Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 (Learning Php, Mysql, Javascript, Css & Html5)The fully revised, updated and extended 4th edition of the hugely popular web development book - includes CSS, HTML5, jQuery and the mysqli extension.... Read More >
PHP and MySQL Web Development (5th Edition) (Developer's Library)PHP and MySQL Web Development (5th Edition) (Developer's Library)

PHP and MySQL Web Development, Fifth Edition

The definitive guide to building database-driven We... Read More >

Secondary WordPress Loops

In coding WordPress plugins and themes, I have often found it necessary to create secondary WordPress loops in the code to show a list of articles or posts on the site that wouldn’t normally appear on the page used to display them. For example, on the homepage of this site, I list articles from three different blog categories in three different lists. The way in which this is accomplished is relatively simple and straightforward.

First, you have to create a new instance of the WP_Query object from WordPress. Due to some complications with the WordPress code, you will need to store the original $wp_query variable in a $temp variable, and override it with your own.  You would do this with something like the following code:

<?php 
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query(); 
?>

This constructs a new WP Query object for you which you can then use for subsequent calls in the loop.  Once you’ve constructed this object, you will want to define your query variables and run your query.

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = 'cat=5&paged=' . $paged;    // Query to pull posts from category ID 5
$wp_query->query($query);  // Run the query on the $newposts object.
?>

Now that you have retrieved the necessary posts from your blog, you can begin your secondary loop.  The format is slightly different however, in that you should run the have_posts() methods on the new object, rather than as WP functions as is seen below.

<?php
if ($wp_query->have_posts()) :
  while ($wp_query->have_posts()) :
    $wp_query->the_post();
?>

… regular loop style WP code such as…

<li>
  <a href="<?php the_permalink() ?>" rel="bookmark"
     title="Permanent Link to <?php the_title(); ?>"
     ><?php the_title(); ?></a>
</li>

… then close the loop.

<?php endwhile; endif; ?>

If necessary you can also add paging controls with the following:

<div class='navigation'>
  <div class='alignleft'>
    <?php next_posts_link('&laquo; Older Entries') ?>
  </div>
  <div class='alignright'>
    <?php previous_posts_link('Newer Entries &raquo;') ?>
  </div>
</div>

Finally, you need to restore the original $wp_query variable with what you stored in $temp.

<?php $wp_query = null; $wp_query = $temp; ?>

I’d love to hear your feedback on this or if you have any suggestions to improve it.  Feel free to comment.

Related Reading:

WordPress Websites Step-by-Step: The Complete Beginner's Guide to Creating a Website or Blog With WordPressWordPress Websites Step-by-Step: The Complete Beginner's Guide to Creating a Website or Blog With WordPress

Have you ever wanted to create a website but found it too complicated or confusing? You're not alone.

It's true that WordPress is the easi... Read More >

WordPress: Creating Visual Web & Membership sites using Beaver Builder and Insta-MemberWordPress: Creating Visual Web & Membership sites using Beaver Builder and Insta-MemberWordPress is possibly the number one tool on the Internet today for creating and maintaining web sites. It is estimated at six out of ten sites on th... Read More >