The below php code results pagination as 1, 2, 3, 4, 5, 6 , …
I would like to get the result as 1, 2, 3, … ,10
if ( is_array( $pages ) ) {
$paged = ( get_query_var( 'paged' ) == 0 ) ? 1 : get_query_var( 'paged' );
echo '<ul class="page-numbers nav-pagination links text-center">';
foreach ( $pages as $page ) {
$page = str_replace( 'page-numbers', 'page-number', $page );
echo '<li>' . $page . '</li>';
}
echo '</ul>';
}
?>
2
Answers
I want to share an example.
Adding dots between numbers of pagination
I think it works fine.
Correction: You can fix $i == ‘4’ and add "…" after the number you specified. Or you can find the median value of the $pages array and replace it with 4.
Based on the code I suppose that the
$pages
is an array containing the page numbers 1-10 and you want to get the firstn
and the last number listed.There are several solutions for this depending on the use case.
Solution 1
If the listing always starts at
1
and you can hard-code the first three elements and the ellipsis and only add the last page number to the list:Solution 2
If for some reason you have to iterate through the whole
$pages
array, then you can add an ellipsis after the n-th element and don’t print for the rest but for the last one:Solution 3
You can also use some advanced indexing to get the first n elements plus the last one and run the loop only for those (this also works if the page numbers are not 1,2,3,…)