When inside The Loop, I want to get the current number of posts.
For example, after every 3 posts I want to insert an ad.
So how do I get the loop value?
You can use the current_post element of a WP_Query object to get the current post iteration;
current_post
WP_Query
while ( have_posts() ) : the_post(); // your normal post code if ( ( $wp_query->current_post + 1 ) % 3 === 0 ) { // your ad code here } endwhile;
Note that if you use this inside a function, you need to globalize $wp_query .
$wp_query
Why not increase the variable and then show your ads as needed?
while(LOOP) echo $i%3==0 ? $ad : ''; $i++
I donβt know why, but the proposed methods did not work for me, I had to resort to the following
$loop_counter = 1; while( $query->have_posts() ) { //Do your thing $query->the_post(); etc $loop_counter++; }
It's safer to play with globals if you ask me.