Reputation: 11
I want to limit the number of pages displayed on my pagination php script below. This was a script made a few years back for me, and although I have read through similar problems on here, their coding is very different.
Any help with this would be really appreciated.
Here is my current script:
<?php
if ($max_pages>1) {
echo "<br>";
if ($page>0) {
echo '<a href="'.$base_url.$sites_directory.($category_id==0?($page==1?'':($page-1).'/'):$category_id.'/'.$paginate[0].($page==1?'':'_'.($page-1)).'/').'" class="pagination">Previous</a>';
}
for ($x=0;$x<$max_pages;$x++) {
if ($page<>$x) {
echo '<a href="'.$base_url.$sites_directory.($category_id==0?($x==0?'':$x.'/'):$category_id.'/'.$paginate[0].($x==0?'':'_'.($x)).'/').'" class="pagination">'.($x+1).'</a>';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo '<a href="'.$base_url.$sites_directory.($category_id==0?($page==($max_pages-1)?'':($page+1).'/'):$category_id.'/'.$paginate[0].($page==($max_pages-1)?'':'_'.($page+1)).'/').'" class="pagination">Next</a>';
}
}?>
Upvotes: 1
Views: 408
Reputation: 57388
Your current script cycles $x
between 0 and $max_pages
.
What you can do is first replace them with $from_page
and $to_page
:
$from_page = 0;
$to_page = $max_pages;
...
for ($x=$from_page; $x < $to_page; $x++)
at which point the script will work just as before.
Now if you want to only display from $N
pages before to $N
pages after $page
,
$N = 5; // display 5+5+1 = 11 pages
$from_page = $page - $N; if ($from_page < 0) $from_page = 0;
$to_page = $from_page + 2*$N+1; if ($to_page > $max_pages) $to_page = $max_pages;
$from_page = $to_page - 2*$N-1; if ($from_page < 0) $from_page = 0;
Not the most elegant way perhaps, but it will try to fit an 11-page area centered on the current page. You may want to also display a link to pages 0 and $max_pages-1
.
<?php
if ($max_pages>1)
{
$N = 5; // display 5+5+1 = 11 pages
$to_page = min($max_pages, max(0, $page - $N) + 2*$N+1);
$from_page = max($to_page - 2*$N-1, 0);
echo "<br>";
if ($page > 0)
{
echo '<a href="'.$base_url.$sites_directory.($category_id==0?($page==1?'':($page-1).'/'):$category_id.'/'.$paginate[0].($page==1?'':'_'.($page-1)).'/').'" class="pagination">Previous</a>';
}
for ($x=$from_page; $x < $to_page; $x++) {
if ($page != $x) {
echo '<a href="'.$base_url.$sites_directory.($category_id==0?($x==0?'':$x.'/'):$category_id.'/'.$paginate[0].($x==0?'':'_'.($x)).'/').'" class="pagination">'.($x+1).'</a>';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo '<a href="'.$base_url.$sites_directory.($category_id==0?($page==($max_pages-1)?'':($page+1).'/'):$category_id.'/'.$paginate[0].($page==($max_pages-1)?'':'_'.($page+1)).'/').'" class="pagination">Next</a>';
}
}?>
Upvotes: 1