Wordpress loop: get the current message counter inside the loop

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?

+7
loops php wordpress
source share
3 answers

You can use the current_post element of a WP_Query object 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 that if you use this inside a function, you need to globalize $wp_query .

+19
source share

Why not increase the variable and then show your ads as needed?

 while(LOOP) echo $i%3==0 ? $ad : ''; $i++ 
0
source share

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.

0
source share

All Articles