7

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?

3 Answers 3

19

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I 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.
@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.
@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.
0

Why not incrementing a variable then display your ads when needed?

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

Comments

0

Unsure why, but the suggested methods didn't work out 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++;
}

Safer than playing with globals if you ask me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.