Display post X of Y in category

I am trying to display a post number (X) on each single.php, based on what number that post is in it’s category, followed by the total number of posts (Y) in the category.
So if there is 10 posts in my category “photos”, the latest post should be “1/10”.

I found this solution for Y:

Read More
<?php
$category = get_the_category(); 
echo $category[0]->category_count;
?> 

This solution almost does what I want for X, but it is not based on category, and includes all posts:
http://wordpress.org/support/topic/show-post-number#post-1294235

Can anyone help? 🙂

Related posts

1 comment

  1. Okay, this should do, what you want:

    // Fetch all posts in the current post's (main) category
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'cat' => array_shift(get_the_category())->cat_ID,
    );
    $query = new WP_Query($args);
    
    // The index of the current post in its (main) category
    $X = 1;
    $id = get_the_ID();
    foreach ($query->posts as $cat_post)
        if ($id != $cat_post->ID)
            $X++;
        else
            break;
    
    // The number of posts in the current post's (main) category
    $Y = $query->found_posts;
    
    // Now, display what we got...
    echo $X.'/'.$Y;
    

    What is happening?
    We fetch all posts of the current (main) category, ordered by Published date. That way, we already have the total number of posts in that category. Then we iterate through the posts and increment a counter variable to track the index of the current post. Finally, we display these numbers somewhere.

Comments are closed.