Skip to content

Instantly share code, notes, and snippets.

@petenelson
Last active April 26, 2024 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petenelson/8335c12f0786fb659e4a724947fbfec9 to your computer and use it in GitHub Desktop.
Save petenelson/8335c12f0786fb659e4a724947fbfec9 to your computer and use it in GitHub Desktop.
WordPress: get_pagination_counts()
<?php
/**
* Gets pagination counts for a query.
*
* @param WP_Query $query The query, defaults to global wp_query.
* @return array
*/
function get_pagination_counts( $query = false ) {
global $wp_query;
if ( ! $query instanceof \WP_Query ) {
$query = $wp_query;
}
$results = [
'found_posts' => 0,
'start' => 0,
'end' => 0,
];
$found_posts = $query->found_posts;
$posts_per_page = $query->query_vars['posts_per_page'];
$current_page = $query->query_vars['paged'];
if ( empty( $current_page ) ) {
$current_page = 1;
}
if ( 1 === $current_page ) {
$start = 1;
} else {
$start = ( ( $current_page - 1 ) * $posts_per_page ) + 1;
}
if ( absint( $current_page ) === absint( $query->max_num_pages ) ) {
$end = $found_posts;
} else {
$end = ( $start + $posts_per_page - 1 );
}
$results['found_posts'] = $found_posts;
$results['start'] = $start;
$results['end'] = $end;
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment