Last active
April 26, 2024 12:21
-
-
Save petenelson/8335c12f0786fb659e4a724947fbfec9 to your computer and use it in GitHub Desktop.
WordPress: get_pagination_counts()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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