How to limit the number of pages shown in a pagination?

Asked

Viewed 2,821 times

6

With this question that already has solution, I got as a result a paginação com PDO but I have one more problem that will possibly be the subject of a reward next week.

As you can see in the image below, I have this pagination with +/- 1000 properties that divided by groups of 12 per page, will return me a total of +/- 90 pages that will be written in pagination form making me have 3 or 4 lines showing numbers that will lose meaning and will look monstrously horrible.

inserir a descrição da imagem aqui

How can I limit the number of pages to be shown by repurposing the code shown within the answered question present in it? If you think it necessary, I will replicate the code inside it here.

  • 1

    I don’t understand... what do you want to limit? The number of linked pages (1 [...] 14)?

  • Like, when I put it straight, it will appear 85 links and I need to limit to 10 for example otherwise it will look horrible this giant amount of links.

  • I believe @Kaduamaral’s answer is what you want.

1 answer

11


It’s easy to do that.

First set a link limit to be displayed before and after:

$lim = 3;

Then set the beginning of the display according to the current page and the limit:

$inicio = ((($pg - $lim) > 1) ? $pg - $lim : 1);

If subtraction is greater than 1, start from it, but not more than 1.

Then set the final limit:

$fim = ((($pg+$lim) < $qtdPag) ? $pg+$lim : $qtdPag);

If the sum is less than the final amount, then finish with it, if not with the final amount.

And finally, define the loop starting and ending with these rules:

if($qtdPag > 1 && $pg <= $qtdPag){
   for($i = $inicio; $i <= $fim; $i++){

      if($i == $pg){
         echo "<li><a class='ativo'>".$i."</a></li>";
      } else {
        echo "<li><a href='busca?pg=$i'>".$i."</a></li>";
      }

   }
}

If the user is on page 5, the links that will be displayed are:

[2] [3] [4] 5 [6] [7] [8]
  • It fits me perfectly. Thank you so much for your help. It’s amazing how this class of professionals is united to help each other. Thanks again!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.