87 comentarios en Digg Style Pagination Class

Mis Algoritmos » Blog Archive » Some styles for your pagination

[...] Algoritmos El acordeón que todos necesitamos… « WP Digg Style Pagination Plugin Digg Style Pagination Class [...]

Mis Algoritmos

<strong>How to create a digg and sabros.us style pagination with PHP</strong>

[Demo] [WP-Digg Style Pagination Plugin] [Some Styles for your pagination]

I made a few modifications to the sabros.us’s pagination script, inspired by the original created by strangerstudios.com, it needs a detail, turn it into a dynamic ...


Oye, en el momento que haces click sobre una de las paginas, te refresca la página agregando la línea "?page=n" (parámetro por GET) pero si yo intento utilizarla dentro de una página que ya utiliza el GET hace falta que ponga el ampersan (&) y agregue "page=n". De lo contrario no se podrá utilizar en páginas que ya tengan parámetros.

Victor De la Rocha

@JL de hecho olvidé ese punto, le adicionaré ese detalle.

Mis Algoritmos » Blog Archive » WP Digg Style Pagination Plugin

[...] If you wish to use the pagination in some of your systems programmed by own account you can use the Digg Style Pagination Class. A version easier to implement, using classes for PHP version 4. The implementation is simple, is [...]


A question.....
How can we change the value of parameter that brings the current page value ?
E.G :
Instead of using, page=1, page=2.....page=n......
I would like to use page=20, page=40,page=60,page=80....
(the query is too complicated to change so this is the only way to display each items....)
thanks for the answer

Victor De la Rocha

@LM you can add <strong>$id *= 10;</strong> to the <strong>get_pagenum</strong> function:

[php num=2]function get_pagenum_link($id){
$id *= 10;
return "$this->target?$this->parameterName=$id";
return "$this->target&$this->parameterName=$id";


Great !
I get another trouble.... :-)
Well, it's working perfectly with the id incremented... but the pagination is still frozen on the page 1 even if you click on page 2,3,4,5,6......,n
and of course the button Next and previous doesn't work.......
Any idea ????

Muchas gracias....

Victor De la Rocha

@LM <del datetime="2007-06-07T15:09:05+00:00">ok, I'm understand that. I will try to find a solution to your problem.</del>

The <strong>$_GET['page']</strong> value for <strong>$class->currentPage()</strong> value, you need divide it by 10.

[php num=2]if(isset($_GET['page'])){
$page = $_GET['page'] / 10;


Where Do I need to modify in the pagination.class.php ?

Victor De la Rocha

@LM You don't need to modify the pagination.class.php (only <a href="#comment-5027" rel="nofollow">this</a>). It only need to call the currentPage function with a value divided by 10.

[php num=4-8]$p = new pagination;
$page = $_GET['page'] / 10;


Great !!
it works goods....


Mis Algoritmos » Blog Archive » How to paginate your SQL querys

[...] Mis Algoritmos Hi :) « Digg Style Pagination Class [...]


I'm getting an error with the include of the pagination.class.php (it works only in the same folder)

"Fatal error: Cannot instantiate non-existent class: pagination in......"

is there something i need to add in the pagination.class.php to solve that?


Victor De la Rocha

"Fatal error: Cannot instantiate <strong>non-existent class</strong>: pagination in......"

You need to include the class.


Line 122 reads:

$lastpage = ceil($this->total_pages/$this->limit);

Using ceil you often get an extra blank page at the end. I changed it to

$lastpage = round($this->total_pages/$this->limit);

And it works perfectly.



I find your pagination class adorable! I am a newbie in php and it seems I can't get it working :~(
I have a project for which I coded other kind of pagination (every single page number displays, no matter how many results there are!) which didn't suit my needs. Now I tried to fire up your navigation class but it doesn't work for me. I don't know how can I call it the right way because it always displays my first 10 rows from a database and nothing happens. Can you propose a solution maybe? How does your class know what rows it needs to displays when some other page from your pagination class is called?


I got the class working for general test purposes, but need help configuring it to friendly urls. Say the address is www.mysite.com/archive/site-news If they click the 2nd page it takes them to www.mysite.com/archive/site-news?page=2 but I want it to read www.mysite.com/archive/site-news/2 Can someone help with this?


Well I sort of got it to work, I used:


But this only works when the ending '/' is on the url. There has to be a way that works for both, right?

Victor De la Rocha




Thank you very much, you have an awesome class and thanks for sharing and helping so many!!


"Line 122 reads:

$lastpage = ceil($this->total_pages/$this->limit);

Using ceil you often get an extra blank page at the end. I changed it to

$lastpage = round($this->total_pages/$this->limit);

And it works perfectly."

$lastpage = floor($this->total_pages/$this->limit);

works better


Thanks verymatch for this paging class!


I've got the script mostly working but I'm getting hung up on one aspect. With $p->limit(10) queries that return 15 or more rows work perfectly, however on queries that return less than 15 rows the pagination is not displayed. I'd expect that to happen with less than 10 rows only.

Am I doing something wrong, or do I need to adjust something within the class?



The digg style solution here is great. Do you know how to incorporate this into Movable Type 4? I see that you have a Wordpress solution. It'd be great if this could also work in MT4. Thanks.

Jason Coleman

This is great. Que excellente.

This class implementation looks great, and the way to go for folks comfortable with classes.

What plugin are you using to show code in your posts? I'm looking for a good one.

Victor De la Rocha

Hola @<strong>Monsef</strong>, ¿Que version del plugin estas utilizando?Este problema fue solucionado en la última version de la classe (<a href="http://www.mis-algoritmos.com/wp-content/uploads/pagination.class031.rar" rel="nofollow">la 0.3.1</a>). Intenta descargandola, si siguen los problemas, me dejas un mensaje :)

@<strong>Alex</strong>: Maybe :)

Hi <strong>Jason Coleman</strong> I use the <a href="http://bluesome.net/post/2005/08/18/50/" rel="nofollow">Exec-PHP Plugin</a>.

Mike Grishaver

Nice class.

I also found an issue when dealing with the last page. For example, if I have 21 items, with a limit of 10 items per page, I should get 3 pages.

However, I am only getting 2 pages.

Looking at the code, you have a function called round, this only rounds up if the number is above .5. So it'll round up correctly if you have 25 items, to show 3 pages. But if 21 items, only gives 2 pages.

I changed the function from "round" to "ceil" to round up to the next integer and now it works.

Victor De la Rocha

hmm @Mike Grishaver which is <a href="#comment-8936" rel="nofollow">the solution</a>? =S


Hay mas error en tu classe , beuno 1 error no functiona correctamente con el FreindlyUrl , mustra paginas blancas he probado meter floor o ceil pero sgue iguale 3) cuando selectiona una pagina siempre se muesra la pagina 1 como selectionada asi que no coje la pagina selectionada si tenemos el urlRewriter activado , proba lo

si tienes alguna solucion por fa ayudanos

Gracias :D

Victor De la Rocha

Uff, tienes razón y lo siento pero, no puedo darle gusto al mundo entero. Me contradije pero pues, no veo aún una manera mas simple de hacerlo.

Además, mucho ojo! <strong>Esto no es un plugin</strong> ¡ES UNA CLASE en todo su esplendor! su uso es SIMPLE: lo incluyes en tu scripts y te apoyas de ella para trabajar con alguna de tus aplicaciones. Jamás mencioné que esto fuera un plugin y tampoco que estuviera basado en otro plugin.

Si por alguna razón la paginación de consultas no fuese TU fuerte, intenté describir <a href="http://www.mis-algoritmos.com/2007/06/10/how-to-paginate-your-sql-querys/" rel="nofollow">un ejemplo</a> apoyándome de la clase =S


Any example how to use with MySQL queries?

Victor De la Rocha

yes @bahodir, you can read <a href="http://www.mis-algoritmos.com/2007/06/10/how-to-paginate-your-sql-querys/" rel="nofollow">this</a>


Thank you very much for your great script, works like a charm and easy to use. 5/5 :)


need help
Hi...I am using your pagination class and I need your help. Pagination is working ok when I open the page first time but when I click on page links like 1,2,3,4 ....it says page can not be displayed. I am passing variables with data between pages using URL. When I put my cursor on these links 1,2,3,4,...etc, it doesn't show variables are attached to the url string. like in status bar it shows "http://localhost/filename.php?page=2". If I use another pagination it shows "http://localhost/filename.php?page=2Field=test1find=test2...". Here field and find are variables and test1 and test2 are values given to the variables.Do I need to change some code in the pagination class? Thanks for your nice pagination.


sorry another pagination is like "http://localhost/filename.php?page=2&Field=test1&find=test2".




I am able to pass the parameters with url and pagination is working fine but it doesn't change the records. It just stays at page one and numbers at pagination get changed. Any help?



Hello...I am using limit 10 and your pagination is working fine but its showing results starting from 11(i.e. pagination link 1 starts from 11 to 20, pagination link 2 shows 21 to 30 and so on) and the last page is blank. I tried Floor or round at line 122 but it doesn't help me. I need your help.



Same to me.

I have 25 limit. And I have one blank page at last, chage to "round" or "floor" I dont get last results.


I need Example very simple ... Can you do That ?

(use select of table name of database)

Plz ....

I watting You ..

Andre Medeiros

On line 148 of your class, it reads:

-----------------------------8page adjacents * 2)){

I got a result, with 20 pages, on the 4th page, with something like:

< 1 2 ... 3 4 5 (etc)

In order to solve this, change the "if" statement to:
-----------------------------8page adjacents * 2)){

Other than that, excelent job!


Hi, Thankyou for the class.

I made a modification to one function in your class in order for it to be xhtml compliant since I had problems getting it validated. Basically I added htmlspecialchars(). It now validates properly.

New function follows:

function get_pagenum_link($id){
return str_replace($this->urlF,$id,$this->target);
return "$this->target?$this->parameterName=$id";
return htmlspecialchars("$this->target&$this->parameterName=$id");


Did I tell you, your code simply rocks.. I was waiting for this kind of pagination class and finally found it :)

turboliux blog » Blog Archive » Pamoka. Diegiam Wordpress puslapių numeravimą

[...] įvairiausių šio kodo variacijų, tačiau siūlau rinktis paprastesnį. Galimi du instaliavimo variantai, arba jums teks šitą [...]


Thanks for this script


muy bueno lo tuyo!


Thanks for the code, I was just about ripping my hair out trying to write it myself :)

Ramon Fincken


Not only a perfect pagination but also surrounding items and SEO possibilities!


There is a bug in the class when on the third page of a sequence longer than 7 if using an adjacent value of 1.

It displays: 1 2 ... 2 3 4 ... 5 6

Instead of: 1 2 3 4 5 ...

To fix this, you need to adjust the code at this line:

if ($page < 1 + ($adjacents * 2) {

... and change it to:

if ($page < 1 + ($adjacents * 2) || ($adjacents == 1 && $page == 3)) {


Hello Greg. I had that bug too. And your solution was very good.

But the change is: if ($this->page < 1 + ($this->adjacents * 2) || ($this->adjacents == 1 && $this->page == 3)) {

You forgot to put the "$this" ;) Even so, thanks for solving that bug.


And Victor, thanks very much for your class. Its adorable! Great work!!


I cant make the url friendly pagination work. The page is stagnant and data is not getting refreshed.


Another point is, how can i pass more than one variable via pagination using user friendly url?



Can anyone please suggest, how i can use more than one parameters or user defined parameters. I am using user friendly pagination and it is working fine but cant send more than one variables. This is my present code.


Thanks ,


esta bueno el tutorial buen trabajo man xD ....


ah me olvidaba podrias poner tambien el archivo index.php esk no se su estructura pues si no es muxa molestia desde ya gracias xD....


Please help me ..
how do we this pagination when listing values from mysql db
I don't have any idea


Hola!, estoy tratando de usar esta clase con CodeIgniter y me sale el siguiente error:

A PHP Error was encountered
Severity: 8192
Message: Function eregi() is deprecated
Filename: libraries/pagination.php
Line Number: 57

Podrías actualizar esta clase para las nuevas versiones de PHP?
Gracias de antemano!

Victor De la Rocha

@alfredo: Si sigues interesado, podrías hacerlo tu mismo. Cambiar el eregi por preg_match :)

Peter Browne

Thought I might share my entire solution for paginating html files in a folder, works perfectly, just change the directory to suit!


function dirList ($directory){

// create an array to hold directory list
$results = array();

// create a handler for the directory
$handler = opendir($directory);

// keep going until all files in directory have been read
while ($file = readdir($handler)) {
sort($results, SORT_NUMERIC);
// if $file isn't this directory or its parent,
// add it to the results array
if ($file != '.' && $file != '..')
$results[] = $file;

// tidy up: close the handler

// done!
return $results;


$directory = 'pages';

$dirarray = (dirList($directory));

$total_pages = count($dirarray);

$items_perpage = 1;

$page = intval($_GET['page']);

if((!$page) || (is_numeric($page) == false) || $page<=0 || $page > ceil($total_pages/$items_perpage)) {
$page = 1; //default

$p = new pagination;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="pagstyle.css" rel="stylesheet" type="text/css" />

V Srinath

Your Pagination looks good.

adjacents not works. any idea?


The class file has somewrong!
On the line of 75 ,the "echo" mustbe "return".


Verdaderamente ESPECTACULAR :)

Muchas gracias.


how to use with file read function?


Hola amigos necesito ayuda con la clase de paginacion, kiero ke en ves de hacer los botones de paginacion via href por javascript agregando una funcion pero no me da.. que estoy haciendo mal???
//siguiente button
ESTO SERIA EL ORIGINAL SIN MODIFICACION: if ($this->page < $counter - 1)
//$this->pagination .= "<a href="".$this->get_pagenum_link($next)."" class="next">$n</a>";
ESTO LO KE MODIFICO, PASO EL $this a una variable $jj y se lo agrego a funcion balinks() pero al hacer clic no realiza nada...

{$jj= $this->get_pagenum_link($next);
$this->pagination .= "<a href="#" onclick="javascript:balinks($jj);" class="next">$n</a>";


Victor De la Rocha

No se que intentas hacer, pero definitivamente eso que pones no está bien:

Primero, $jj debería ser código javascript, y ahí lo estas imprimiendo como si fuera código php.
Segunda, no es tan simple como lo pones.

Explicate bien, ¿que quieres hacer?


Hay un bug en esta clase, que hace que cuando no se pasa el parametro $paginacion->currentPage se muestre medio deforme. (puede pasar que $_GET['page'] llegue vacío, por ejemplo)

Quizás podría verse como algo que no es necesario, pero en fin, opté por solucionarlo y compartirlo con ustedes:


Un saludo,

Victor De la Rocha

Muchas gracias Droope.

jay jay

Hope this will also helpful - http://www.phpqa.in/2008/01/pagination-class-in-php.html


This is a WONDERFUL class, and thank you so much!

I can't get the getOutput function to work. Could you please provide an example of how to capture the html output into a variable?

Thank you!


Hi , I found your class useful
But i have problem with using it
I need to display the results from db , but your class does not support DB query ..

Ryan Harne

Last updated 2008, but works well!

Thanks YOU!!


Hi Great plugin, really excellent!

I would like to add a little with a very little feature: possibility to change separator (currently is: "...").
This is needed when, for example, float is required by css.

The changes:
After "var $prevI =" add:
- var $separator = '...';

After "function prevIcon(..." add:
- function separator($value){$this->separator = $value;}

Then replace all "..." with
- $this->separator

$p = new pagination;
$p->separator('<span class="sep">...</span>');



could I show pages of tables instead ? I already have all my data in an array so I would like to display this data without a page refresh only showing the next 10 items from my array?


Thanks for this great pagination script.

Can you add the htaccess code for this pagination?

thanks for all.


I wonder how this plugin work for foreach loop?

Luis Carlos

Deprecated: Function eregi() is deprecated in Pagination.php on line 62


Hello Guys. This pager is very good.
Now i realized the download links for the classes is wrong.
Could you please correct the download url's, please.




How could I modify this so that more than the 2 first and last page numbers are shown?

i.e: 1 2 3 4 --- 13 14 15 --- 34 35 36 37

Posicionamiento Web Asturias

To fix the eregi() error chante the line 62 with:

// change ...
if(eregi('^ *$',$value)){

// with....
if(preg_match('/^ *$/i',$value)){



i have make a wordpress plugin in which i want to fetch data from database
and need to pagination i used digg style pagination but when i click on next link "You do not have sufficient permissions to access this page." this error occour plz help where is problem this is my code

Plugin Name:Register Data
Description:Pagination Plugin for wordpress admin Panel.
Author:Pawan Sharma
Author URI:

$object = new YourPlugin();

//add a hook into the admin header to check if the user has agreed to the terms and conditions.
//add_action('admin_head', array($object, 'adminHeader'));

//add footer code
//add_action( 'admin_footer', array($object, 'adminFooter'));

// Hook for adding admin menus
add_action('admin_menu', array($object, 'addMenu'));

//This will create [yourshortcode] shortcode
add_shortcode('yourshortcode', array($object, 'shortcode'));

class YourPlugin{

* This will create a menu item under the option menu
* @see http://codex.wordpress.org/Function_Reference/add_options_page
public function addMenu(){
add_options_page('Regeter Data', 'Regeter Data', 'manage_options', 'my-unique-identifier', array($this, 'optionPage'));

* This is where you add all the html and php for your option page
* @see http://codex.wordpress.org/Function_Reference/add_options_page
public function optionPage(){
$items = mysql_num_rows(mysql_query("SELECT * FROM wp_register_form;")); // number of total rows in the database

if($items > 0) {
$p = new pagination;
$p->limit(5); // Limit entries per page
$p->currentPage($_GET[$p->paging]); // Gets and validates the current page
$p->calculate(); // Calculates what to show
$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. ?>

<table class="widefat">
<th>Mobile No</th>
$sql = "SELECT * FROM wp_register_form $limit";
$result = mysql_query($sql) or die ('Error, query failed');

if (mysql_num_rows($result) > 0 ) {
while ($row = mysql_fetch_assoc($result)) {
$name = $row['customer_name'];
$city = $row['customer_city'];
$phone = $row['customer_phone'];
$email = $row['customer_email'];
$address = $row['customer_address'];
$id = $row['customer_id'];?>

<td><?php echo $name; ?></td>
<td><?php echo $city; ?></td>
<td><?php echo $phone; ?></td>
<td><?php echo $email; ?></td>
<td><?php echo $address; ?></td>
<td><?php echo "<a href='http://localhost/wor/wp-content/themes/mitfitness/single_details.php?id=".$id."'>View Details</a>"?></td>
<?php }
} else { ?>
<td>No Record Found!</td>
<?php } ?>

* this is where you add the code that will be returned wherever you put your shortcode
* @see http://codex.wordpress.org/Shortcode_API
public function shortcode(){
return "add your image and html here...";


when i click on image for show the details of an image it's not show image id.........why?
please solve this problem.

<link rel="stylesheet" href="diggstyle.css">


$items = 5;
$page = 1;
$dir = 'images';

if(isset($_GET['page']) and is_numeric($_GET['page']) and $page = $_GET['page'])
$limit = " LIMIT ".(($page-1)*$items).",$items";
$limit = " LIMIT $items";

$sqlStr = "SELECT * FROM images ORDER BY image_id";
$sqlStrAux = "SELECT count(*) as total FROM images";

$aux = mysql_fetch_assoc(mysql_query($sqlStrAux));
$query = mysql_query($sqlStr.$limit) or die(mysql_error());

$p = new pagination;


<title>Welcome to our Photo Gallery</title>
<style type="text/css">
th { background-color: #999;}
.odd_row { background-color: #EEE; }
.even_row { background-color: #FFF; }

.size{width:50px; height:50px;}

<p>Click on any image to see it full sized.</p>

<table style="width:100%;">
<th>Uploaded By</th>
<th>Date Uploaded</th>

$odd = true;
while ($row = mysql_fetch_array($query)) {
echo ($odd == true) ? '<tr class="odd_row">' : '<tr class="even_row">';
$odd = !$odd;
echo '<td><a href="' .
'img_detail.php?image_id=' . $image_id .
echo '<img class="size" src="' . $dir . '/' . $row['image_id'] . '.jpg">';
echo '</a></td>';
echo '<td>' . $row['image_caption'] . '</td>';
echo '<td>' . $row['image_username'] . '</td>';
echo '<td>' . $row['image_date'] . '</td>';
echo '</tr>';



echo"There no are records to paginate.";

when i click on image for show the details of an image it's not show image id.........why?
please solve this problem.


Hi. i tried to use that class by including in a php file but it does not working. can you show or tell me that how to use it? i am beginner at php so i need full working code. thanks


This is great class and I liked it, However I was wondering how could I set page number to page 1 if the page number is less than 1 or is not numeric or greater than the total page numbers. Users might mess up with the parameter value in the url and in that case I just wanna send them to page 1. I tried something like the below but it doesn't work. Any help would be great.

if($_GET['pgn'] < 1 || !is_numeric($_GET['pgn']) || $_GET['pgn'] > $tot){//$tot is total pages
$page = 1;
$page = 1;


I like this pagination class however I am having hard time figuring out, how to make the url friendly work?
i have

and when I click on the next button it only changes the url but the page doesn't get to page 2. so how does this work? I also tried removing the number sign and replacing it with my page number however that gets to me 500 internal server error. I really need help please.

Deja un comentario

¿Cuanto es 2 + 3 - 5? =

Suscribirse a los comentarios.