Wordpress loop : get current post count inside The Loop
14,570
You can use the current_post
member of the WP_Query
object instance to get the current post iteration;
while ( have_posts() ) : the_post();
// your normal post code
if ( ( $wp_query->current_post + 1 ) % 3 === 0 ) {
// your ad code here
}
endwhile;
Note, if you're using this inside a function, you'll need to globalise $wp_query
.
Related videos on Youtube
Author by
Kartik Rao
Updated on June 04, 2022Comments
-
Kartik Rao almost 2 years
When inside The Loop, I want to retrieve the current post count.
For example, after every 3 posts, I want to insert an ad.
So, how do I get the value of the loop count?
-
Kartik Rao almost 14 yearsI tried this method. The ad is being inserted before and after every 3 posts! How do i get it to insert the ad only after 3 posts.
-
Adam McArthur almost 9 years@KartikRao For future reference, this answer is ever so slightly flawed. Since indexes start at 0, the first time the conditional is run (the first iteration of the while loop), it will actually return
true
because 0 modulus any real number is always 0. The ad code is being incorrectly inserted before your first post, fourth post, seventh post - etc. Updated code should read:($wp_query->current_post + 1) % 3
. -
Mark Amery almost 9 years@AdamMcArthur inserting the ad code before the fourth and seventh posts is correct given the question description saying ads should be inserted "after every 3 posts". You're right that inserting an ad before the first post doesn't match spec, but your proposed fix - which would insert ads after the 2nd/5th/8th posts instead of the 3rd/6th/9th posts as requested - doesn't either.