1

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:

<?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? :-)

  • How do you want to order the posts? Published date? Modified date? ID? Alphabetical? – tfrommen Dec 30 '13 at 22:08
  • @t f by published date :) – Cody Dec 30 '13 at 22:11
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.

  • 1
    @t f - you just saved my night! Thank you SO MUCH! Happy new year :-) – Cody Dec 30 '13 at 22:37

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.