Last active
December 18, 2015 15:59
-
-
Save sscovil/5808376 to your computer and use it in GitHub Desktop.
Add this function to your WordPress theme's `functions.php` file and call it from `archive.php` using the template tag `my_archive_post_count()`. If $echo parameter is set to false, it will simply return the HTML as a string. Post count is appended with previous- and next page links if there is more than one page.
This file contains hidden or 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 | |
function my_archive_post_count( $echo = true ) { | |
global $wp_query; | |
$showing = ''; | |
if ( $wp_query->found_posts > 1 ) { | |
// Get previous & next page links. | |
$args = array( | |
'sep' => ' — ', | |
'prelabel' => __('« Previous'), | |
'nxtlabel' => __('Next »'), | |
); | |
$page_links = get_posts_nav_link( $args ); | |
// Calculate post range based on posts per page and total posts found. | |
$page_number = is_paged() ? $wp_query->query_vars['paged'] : 1; | |
$current_max = ( get_option( 'posts_per_page' ) * ( $page_number - 1 ) ) + $wp_query->post_count; | |
$current_min = $current_max - $wp_query->post_count + 1; | |
// Prepare post counts for display. | |
$range = ( $current_min == $current_max ) ? strval( $current_min ) : $current_min . '-' . $current_max; | |
$total = $wp_query->found_posts; | |
// Create HTML string for output. | |
$showing = | |
'<div class="showing" style="margin-right:1em;">' | |
. 'Currently viewing ' . $range . ' of ' . $total . ' articles. ' | |
. $page_links . '<div>' | |
; | |
} | |
if ( true === $echo ) echo $showing; | |
return $showing; | |
} |
Thanks man, this came in useful for me, though I didn't use it on the archives page, I used it to display the count of posts on the index.php.
Saved my day! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The original version did not accurately calculate post counts on the last page; updating it now and turning it into a function.