0

I'm using custom post types and taxonomies to organize posts into different series where the order of the posts is important (travel narratives).

My plan for the single-{custom-post-type}.php was to display each post's position within the series:

  • Post 3/7 in TAXONOMY TERM

I'm currently using the following standard WP_Query to find the total number of posts in each taxonomy:

$query = new WP_Query(array(
    'TAXONOMY' => 'TAXONOMY TERM', 
    'posts_per_page' => -1, 
    'post_status' => 'publish'
));
echo $query->post_count;

However, I have been unable to figure out how to find the current post's position within the series.

Post ?? / echo $query->post_count

I was considering using WP_Query's date parameters (before), but because it only accepts DD, MM, YYYY it wouldn't really work if there were more than one post published in a day.

I may be going about this the wrong way, so I am definitely open to other interpretations of how to solve this problem.

Thanks in advance!

3

If the post order reflect the publishing date (and note that publishing date also takes into account hour, minute and second of publication) than is pretty easy to get the order, using a query that return only post ids and then array_search to find current post id index:

$query = new WP_Query( array(
    'TAXONOMY' => 'TAXONOMY TERM', 
    'posts_per_page' => -1, 
    'post_status' => 'publish',
    'orderby' => 'date', // be sure posts are ordered by date
    'order' => 'ASC', // be sure order is ascending
    'fields' => 'ids' // get only post ids
));

global $post; // current post object

$i = array_search( $post->ID, $query->posts ) + 1; // add 1 because array are 0-based

echo "Post {$i} / {$query->post_count} in TAXONOMY TERM";
  • That's awesome, thanks! I'm using the date to order as manually assigning an order seemed way too tedious, so this works perfectly for my needs. – Stephen S. May 30 '14 at 21:21

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.