Jump to content

Pagination Page Display


Go to solution Solved by mac_gyver,

Recommended Posts

Greetings all,

 

So, I'm working on my page navigation and I'm having a little trouble with my math here. It's probably a brain freeze from too much coding in one day but anyhow. What I'm trying to get my code to do is always show 9 pages and never show anymore then 9 pages in the navigation. Unfortunately that's not the result that I am getting with this script.

// List page selectors.
for($j = max(1, $current_page - ; $j <= min($current_page + 8, $total_pages); $j++) {
  $p = $j;
  echo "<a href='?p=" . $p . "'>" . $p . "</a> ";
}

I have a different script for the first page, previous page, next page and last page links. They all work fine of course since those are super easy scripts.

Any help would be appreciated.

 

Best Regards,

Nightasy

Edited by Nightasy
Link to comment
https://forums.phpfreaks.com/topic/280379-pagination-page-display/
Share on other sites

  • Solution

// calculate current_page +/- 4, limited by 1/total_pages
$start = max(1, $current_page - 4);
$end = min($current_page + 4, $total_pages);

// if start resulted in 1, make end = start + 8
if($start == 1){$end = $start + 8;}
// if end resulted in total_pages, make start = $end - 8
if($end == $total_pages){$start = $end - 8;}

// limit start/end to 1/total_pages
$start = max(1, $start);
$end = min($end, $total_pages);

for($p = $start; $p <= $end; $p++) {
    if($p == $current_page){
        echo "[$p] "; // current_page not a link
    } else {
        echo "<a href='?p=$p'>$p</a> ";
    }
}

@mac_gyver : YES, this makes so much sense. Thank you very much. I actually had to walk away from my computer trying to figure this out. It was getting frustrating. Now that I see your code it's so obvious. Much appreciated!!!

 

 

Edit:

Oh, I kind of got rid of this little bit here:

if($p == $current_page){
        echo "[$p] "; // current_page not a link
    } else {

It was throwing my divs all out of wack lol. This works great though and is exactly what I wanted. Thank you again!

Edited by Nightasy
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.