Monday, June 4, 2007

Getting a Count of Posts in The Loop in WordPress

I had a hard time finding this information. Here's how you can get a count of the number of posts in your current loop and the index of the current post you're accessing. post_count starts at zero and current_post starts at 1. In this example, I'm outputting a horizontal rule after all posts except the last one in the loop.

<?php
/* From http://codex.wordpress.org/The_Loop_in_Action */
if( ($wp_query->current_post + 1) < ($wp_query->post_count) )
{
echo("<hr />");
}
?>

8 comments:

Jules said...

You've solved my problem, thanks. I needed a way to break a list of posts into two columns.

Diablien said...

THANK YOU THANK YOU THANK YOU.

I couldn't find anywhere how to just get the post count for the # of posts in the current loop. Thank you for showing me:
$my_post_count = $wp_query->post_count;

floglaser said...

awesome! thanks a lot. saved my day!

Michael said...

Brilliant little snippet of code! Exactly what I was looking for. Thank you!

Arturo said...

What would be the solution using get_posts() instead of wp_query()?

I haven´t found the way to get the number of posts in this way.

para said...

thanks so much!!

Bao said...

saved my day! thanks you so much!!!

babai said...

Dear @Arturo, for get_posts() its simple, before get_posts() you are anyway going to do query_posts(), here get a return value, example
$d = query_posts(.....);
now just do a array count for the returned element ...

$count = sizeof($d);

and you are done