Calculate page count using PHP Maths and Round

I have a certain number of potential posts. We do not know how many there are, but the system is configured to display 12 pages. Below I would like it to display the number of pages.

So, if we get the messages:

<?php $pages = get_posts('category_name=news'); ?> 

Now what we want to do is

  • determine how many messages it found.
  • divide this number by 12
  • round this number to the nearest integer (UP never go down)
  • divide this number by 1 and indicate how many times 1 goes into it.
  • thus setting as many page numbers as necessary.

Ideas are to line up like 1 | 2 | 3 | 4 | 5 etc.

Any ideas?

+4
source share
2 answers

You already think about it. If you know the number of results and the maximum number of results per page, then you know how many pages you need. I suppose this is WordPress because you used get_posts so that it returns an array containing the posts, therefore:

 <?php $max_per_page = 12; //Max results per page $posts = get_posts('category_name=news'); $total_posts = count($posts); //Total number of posts returned $pages = ceil($total_posts / $max_per_page); for($i = 1;$i <= $pages;$i++) { echo '<a href="?page=' . $i . '">' . $i . '</a>'; //Or whatever the link needs to be if($i != $pages) { echo "|" } } ?> 
+8
source
  • find out how many posts he found

    SELECT COUNT(*) FROM *table* WHERE *conditions*...

  • divide this number by 12

    SELECT COUNT(*)/12 AS num_pages FROM *table* WHERE *conditions*...

    OR

    $count = mysql_query(*see #1*)/12.0; // NOT JUST 12!

  • round this number to the nearest integer (UP never down)

    $count = ceil($count);

  • divide this number by 1 and indicate how many times 1 goes into it.

    REALLY?? DIVIDING ANY NUMBER FOR 1 RETURNS HIMSELF!

  • thus indicating as many page numbers as necessary.

    Not really. How do you know which specific page the user is currently on for? How do you plan to actually occupy the pages? If the messages are already filled, you spend 1-2 requests each time, just for pagination.

Basically you are trying to do pagination, but without knowing a lot of SQL, you better use the existing solution (or at least rephrase the existing code to limit queries)

+1
source

Source: https://habr.com/ru/post/1344285/


All Articles