How To Add Pagination Into List of Records or WordPress Plugin

How To Add Pagination Into List Of Records Or WordPress Plugin

Often in many application, such as in WordPress Plugin, we will need to deal with list of records. As the records grow, more records will need to be displayed. There is a catch though, if you retrieve all the records at one go because it will slow the system down.

In order to have a better user experience for record listing, paging comes into play. It’ll not only help to organize the records by limiting the number of records you want to show per page, it also cuts the down the time of retrieving records. Therefore, pagination plays a very important part in providing a great user experience when interacting with the data.

Adding Pagination

Imaging if you have a list of 1000 or more records that you want to display. Without pagination, listing all the records will definitely take quite awhile and also increase the load for the database server when executing the query. This is not very efficient, even though retrieving records from database can be cheap.

Now let’s say we want to add in pagination into the 1000 records, by specifying the limit, it will only shows the exact amount of records you want to view. This is a huge benefit for the database server load, because we are not retrieving all the records at once.

Below examples are 2 different type of pagination and a demo on how to add pagination into WordPress Plugin.

Simple PHP Pagination Class

Copy the following code and save as pager.php, this file will be the pagination class. With this pagination class from Happycodings, it’d help us add pagination to the list of records easily.

<?php
function findStart($limit) { 
	if ((!isset($_GET['page'])) || ($_GET['page'] == "1")) { 
    	$start = 0; 
    	$_GET['page'] = 1; 
    } else { 
       	$start = ($_GET['page']-1) * $limit; 
    } 
	return $start; 
}
 
  /*
   * int findPages (int count, int limit) 
   * Returns the number of pages needed based on a count and a limit 
   */ 
function findPages($count, $limit) { 
     $pages = (($count % $limit) == 0) ? $count / $limit : floor($count / $limit) + 1; 

     return $pages; 
} 

/* 
* string pageList (int curpage, int pages) 
* Returns a list of pages in the format of "« < [pages] > »" 
**/ 
function pageList($curpage, $pages) 
{ 
	$page_list  = ""; 

    /* Print the first and previous page links if necessary */ 
    if (($curpage != 1) && ($curpage)) { 
       $page_list .= "  <a href=\" ".$_SERVER['PHP_SELF']."?page=1\" title=\"First Page\">«</a> "; 
    } 

    if (($curpage-1) > 0) { 
       $page_list .= "<a href=\" ".$_SERVER['PHP_SELF']."?page=".($curpage-1)."\" title=\"Previous Page\"><</a> "; 
    } 

    /* Print the numeric page list; make the current page unlinked and bold */ 
    for ($i=1; $i<=$pages; $i++) { 
    	if ($i == $curpage) { 
         	$page_list .= "<b>".$i."</b>"; 
        } else { 
         	$page_list .= "<a href=\" ".$_SERVER['PHP_SELF']."?page=".$i."\" title=\"Page ".$i."\">".$i."</a>"; 
        } 
       	$page_list .= " "; 
      } 

     /* Print the Next and Last page links if necessary */ 
     if (($curpage+1) <= $pages) { 
       	$page_list .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".($curpage+1)."\" title=\"Next Page\">></a> "; 
     } 

     if (($curpage != $pages) && ($pages != 0)) { 
       	$page_list .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".$pages."\" title=\"Last Page\">»</a> "; 
     } 
     $page_list .= "</td>\n"; 

     return $page_list; 
}
 
/*
* string nextPrev (int curpage, int pages) 
* Returns "Previous | Next" string for individual pagination (it's a word!) 
*/ 
function nextPrev($curpage, $pages) { 
 $next_prev  = ""; 

	if (($curpage-1) <= 0) { 
   		$next_prev .= "Previous"; 
	} else { 
   		$next_prev .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".($curpage-1)."\">Previous</a>"; 
	} 

 		$next_prev .= " | "; 

 	if (($curpage+1) > $pages) { 
   		$next_prev .= "Next"; 
    } else { 
       	$next_prev .= "<a href=\"".$_SERVER['PHP_SELF']."?page=".($curpage+1)."\">Next</a>"; 
    } 
     	return $next_prev; 
    } 
} 
?> 

Once you have the pager.php, instantiate the class as below. Change the $limit to your desired number of records to show per page and finally get the page list by echoing it out.

/* Instantiate class */ 
require_once("pager.php"); 
$p = new Pager; 

/* Show many results per page? */ 
$limit = 100; 

/* Find the start depending on $_GET['page'] (declared if it's null) */ 
$start = $p->findStart($limit); 

/* Find the number of rows returned from a query; Note: Do NOT use a LIMIT clause in this query */ 
$count = mysql_num_rows(mysql_query("SELECT field FROM table")); 

/* Find the number of pages based on $count and $limit */ 
$pages = $p->findPages($count, $limit); 

/* Now we use the LIMIT clause to grab a range of rows */ 
$result = mysql_query("SELECT * FROM table LIMIT ".$start.", ".$limit); 

/* Now get the page list and echo it */ 
$pagelist = $p->pageList($_GET['page'], $pages); 
echo $pagelist; 

/* Or you can use a simple "Previous | Next" listing if you don't want the numeric page listing */ 
//$next_prev = $p->nextPrev($_GET['page'], $pages); 
//echo $next_prev; 
/* From here you can do whatever you want with the data from the $result link. */ 

Digg Style Pagination

As the above simple pagination class is enough for us to display a list of page numbering for the records, but what will happen if there are a few hundreds of pages, isn’t the row of page numbering going to be very long too?

Here is another nice Digg Style Pagination class that you can consider if you think there will be a lot of pages for your records.

Download the pagination.class.php.

Go through the guide to customize the style or desired output for the paging you want. Now, to give you a clearer view on how to add this Digg Style Pagination class. Check out below to find out how to add the Digg Style Pagination to a WordPress Plugin.

How To Add Pagination To WordPress Plugin?

If you are building a WordPress plugin that require to display a list of records from database. As records get huge, you will need to have pagination so that you can organize your records well.

Wordpress Plugin with Digg Style Pagniation

First, you will need to download the pagination.class.php and save it in your WordPress Plugin folder.

Next, in the PHP file that you want to list your records, insert the following code. Below are some of the methods we used from the pagination class. For the full list of methods, please refer to Digg Style Pagination Class Help Page.

Note that you will need to change the SQL query, pagination class configuration and table fields, in order to work nicely with your WordPress Plugin.

<?php

$items = mysql_num_rows(mysql_query("SELECT * FROM wp_table;")); // number of total rows in the database

if($items > 0) {
		$p = new pagination;
		$p->items($items);
		$p->limit(30); // Limit entries per page
		$p->target("admin.php?page=list_record"); 
		$p->currentPage($_GET[$p->paging]); // Gets and validates the current page
		$p->calculate(); // Calculates what to show
		$p->parameterName('paging');
		$p->adjacents(1); //No. of page away from the current page
				
		if(!isset($_GET['paging'])) {
			$p->page = 1;
		} else {
			$p->page = $_GET['paging'];
		}
		
		//Query for limit paging
		$limit = "LIMIT " . ($p->page - 1) * $p->limit  . ", " . $p->limit;
		
} else {
	echo "No Record Found";
}

?>

//Now we'll display the list of records

<div class="wrap">
	<h2>List of Records</h2>

<div class="tablenav">
    <div class='tablenav-pages'>
        <?php echo $p->show();  // Echo out the list of paging. ?>
    </div>
</div>

<table class="widefat">
<thead>
	<tr>
		<th>ID</th>
		<th>Full Name</th>			
		<th>Email</th>
	</tr>
</thead>
<tbody>

$sql = "SELECT *  FROM $wp_table ORDER BY id DESC $limit";
$result = mysql_query($sql) or die ('Error, query failed');

if (mysql_num_rows($result) > 0 ) {
	while ($row = mysql_fetch_assoc($result)) {
            $id             = $row['id'];
            $fullname  = $row['fullname'];
            $email       = $row['email'];

        <tr>
            <td><?php echo $id; ?></td>
            <td><?php echo $fullname; ?></td>
            <td><?php echo $email; ?></td>	
        </tr>
<?php } 
} else { ?>
        <tr>
	    <td>No Record Found!</td>
        <tr>	
<?php } ?>
</tbody>
</table>
</div>

Now you know How to Add a Digg Style Pagination to a WordPress Plugin, it should make your listing of data much more efficient. Pagination saves your time and bandwidth so you can concentrate more on other implementing issues.

Still not sure about this tutorial on adding pagination? Or simply have an idea to share? Feel free to contact us or leave a comment here!

Comments

    • 9sh,
    • June 28, 2009
    / Reply

    very helpful and useful

    • khalid,
    • July 23, 2009
    / Reply

    this page gave the best result for Pagination… I was searching for a good solution for last 3 days…..
    hats off to u….. onextrapixel.com team…..

    • Pravin,
    • September 17, 2009
    / Reply

    Bud,
    Thanks for the tutorial!Here the Pagination is done without reloading the page?

    Cheers,
    Pravin.

    • Dan,
    • October 1, 2009
    / Reply

    Great! Can this be used with wp_list_bookmarks() to create pagination for my long list of bookmarks?

    Thanks
    Dan

    • Md Shahid,
    • December 2, 2009
    / Reply

    Hi..

    This is so good. Good job.
    Thanks

    • Phillip,
    • December 31, 2009
    / Reply

    This sounds exactly like what I want to implement but I can’t get it to work. I”m using the Simple PHP pagination class example.
    I put the pager.php file in the root of my template directory and the rest of the code in my page. All I’m gettting is the code from from the instantiation displayed on my page. No errors. Can you elaborate more on implementation?

    Thanks

  1. / Reply

    thnx for this wonderful post,helped me in adding pagination to my personal plugin.

  2. / Reply

    How did you or what code did you use to add the actions (edit, delete) to the table.

    1. / Reply

      Nevermind, thanks

    • aeda,
    • July 21, 2010
    / Reply

    hi sir

    how to do if my pagination have first and last page instance of prev and next only…
    can give the coding…

    can nu help me sir…………

  3. / Reply

    I dont get what you have done for wordpress. I successfully limited the out put but I dont know how to out put the buttons for navigation.

  4. / Reply

    Thank you very much. Great tutorial. But i am having problem to paginate at admin panel. it’s showing “You do not have sufficient permissions to access this page.” Please help me. Thanks.

      • ashr4y,
      • August 9, 2011
      / Reply

      I had the same problem. If you are using the Digg style pagination class file, change lines 83 to 89 with a single line for function get_pagenum_link:

      return add_query_arg( $this->parameterName, $id );

        • Lance,
        • October 16, 2012
        / Reply

        Thank you so much, I’ve been stuck on that forever.

        Made your change, works like a charm now. :) :) :) :)

    • Andrea,
    • November 21, 2011
    / Reply

    The method $p->show() don’t return anything, even error.
    You know why?
    Thanks

  5. / Reply

    100 out of 100 it work for my site thxsssssss

    • Deepa,
    • February 23, 2012
    / Reply

    Hi
    Could anyone please send me the pagination.class.php file. I am not able to download the file.
    Thanks

      • Peter,
      • March 20, 2012
      / Reply

      The link for the pagination.class.php is broken, does anyone know another place where we can download it?

    • David Woodfin,
    • April 25, 2012
    / Reply

    Hi,

    Thanks for your comment. I’m glad you find this collection useful.

    Thanks

    • Prasad,
    • July 5, 2012
    / Reply

    Nice script.
    Thank you very much.:)

    • Kyle,
    • October 5, 2012
    / Reply

    Link for the Digg style class is down and I can’t find a copy anywhere :(

  6. / Reply

    really awesome.. its really help me to solve a problem. thanks

  7. / Reply

    can anyone please help me with WordPress query?

    The script is working fine for the first page in my WordPress But when it calls another page..it shows no results. Here is my query:

    $retrieve_data = $wpdb->get_results( “SELECT * FROM $table_name ORDER BY item_id DESC LIMIT “.$limits.”,”.$max );
    foreach ( $retrieve_data as $data)
    {echo data….}

    For example when I go to 2nd page then the url is like…example.com/product-list/?pg=2 and it shows no data.

    can anyone please help me?

    • webduos,
    • May 16, 2013
    / Reply

    I dont get what you have done for wordpress. I successfully limited the
    out put but I dont know how to out put the buttons for navigation.

    thanks

  8. / Reply

    Hi,
    I faced to the following error message after clicked the pagination numbers.
    “You do not have sufficient permissions to access this page.”

    I changed the $p->target(“admin.php?page=list_record”); by changing admin.php.(plugin admin page, pagination.class.php…etc )
    But not success.
    So full url is,
    http://example.com/wp-admin/admin.php?page=list_record&paging=2

    Please help me?

Leave a Reply

Your email address will not be published. Required fields are marked *

Deals

Iconfinder Coupon Code and Review

Iconfinder offers over 1.5 million beautiful icons for creative professionals to use in websites, apps, and printed publications. Whatever your project, you’re sure to find an icon or icon…

WP Engine Coupon

Considered by many to be the best managed hosting for WordPress out there, WP Engine offers superior technology and customer support in order to keep your WordPress sites secure…

InMotion Hosting Coupon Code

InMotion Hosting has been a top rated CNET hosting company for over 14 years so you know you’ll be getting good service and won’t be risking your hosting company…

SiteGround Coupon: 60% OFF

SiteGround offers a number of hosting solutions and services for including shared hosting, cloud hosting, dedicated servers, reseller hosting, enterprise hosting, and WordPress and Joomla specific hosting.