Consider using $current_post instead of loop counters

It is common while working with the Loop in WordPress to set up a loop counter when you want to style your first post; another basic use case for loop counters is to insert an ad between your posts.

if ( have_posts() ) :

    // setting up the loop counter
    $counter = 0;

    while ( have_posts() ) : the_post();

        the_title(
            sprintf(
                '<h2><a href="%s" rel="bookmark">',
                esc_url( get_permalink() )
            ),
            '</a></h2>'
        );

        // is this the fourth post?
        if ( 3 == $counter ) {

            get_template_part( 'parts/ads', 'between-posts' );

        }

        the_content();

        // incrementing the loop counter
        $counter++;

    endwhile;

endif;

While setting a loop counter is a straightforward solution you might want to consider using the $current_post property which is avaliable when you are interacting with WP_Query. It does save you from initalizing and incrementing the loop counter over and over again.

Note: current_post starts is zero-based, counting starts from 0.

if ( have_posts() ) :

    while ( have_posts() ) : the_post();

        // using the built in current_post avaliable for every WP_Query
        if ( 3 == $wp_query->current_post ) {

            get_template_part( 'parts/ads', 'between-posts' );

        }

    endwhile;

endif;

If you are not using the default loop just make sure you replace $wp_query with the variable in which you saved the data returned from WP_Query.

$movies = new WP_Query( [
    'post_type' => 'movie',
] );

if ( $movies->have_posts() ) :

    while ( $movies->have_posts() ) : $movies->the_post();

        // using $movies instead of $wp_query
        if ( 3 == $movies->current_post ) {

            get_template_part( 'parts/ads', 'between-posts' );

        }

    endwhile;

    wp_reset_postdata();

endif;

Did you find this article useful, interesting or you want to chat about this topic? Send me a mail and let me know. In case you found some spelling or grammar mistakes let me know that too.