Skip to content

Instantly share code, notes, and snippets.

@sscovil
Last active December 18, 2015 15:59
Show Gist options
  • Save sscovil/5808376 to your computer and use it in GitHub Desktop.
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.
<?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' => ' &#8212; ',
'prelabel' => __('&laquo; Previous'),
'nxtlabel' => __('Next &raquo;'),
);
$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;
}
@sscovil
Copy link
Author

sscovil commented Jun 25, 2013

The original version did not accurately calculate post counts on the last page; updating it now and turning it into a function.

Copy link

ghost commented Jun 19, 2014

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