I'm currently using this class in my single blog posts to get a total post count and number my posts (post 89 of 90, etc...)

class MY_Post_Numbers {

private $count = 0;
private $posts = array();

public function display_count() {
    $this->init(); // prevent unnecessary queries
    $id = get_the_ID();
    echo sprintf( '<div class="post-counter">Post number<span class="num">%s</span><span class="slash">/</span><span class="total">%s</span></div>', $this->posts[$id], $this->count );

private function init() {
    if ( $this->count )
    global $wpdb;       
    $posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date " ); // can add or change order if you want 
    $this->count = count($posts);

    foreach ( $posts as $key => $value ) {
        $this->posts[$value] = $key + 1;
$GLOBALS['my_post_numbers'] = new MY_Post_Numbers;
function my_post_number() {

I would like to make it category specific. Is that possible? So instead of 89 of 90 it will say 8 of 10 because it's only looking within that post's specific category.


Raw SQL is inconvenient.

You can use get_posts() (or WP_Query which it wraps) with 'fields' => 'ids' (see fields parameter ) for lightweight counting, while retaining compatibility with all arguments it accepts, including category parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.