Inserts ads between posts

Does your project call for you to insert an ad, graphic, or some other type of content between posts? If so, there’s a very easy solution.

A typical loop looks like this, taken from the twentyfourteen theme:

if ( have_posts() ) :
  while ( have_posts() ) : the_post();
    get_template_part( 'content', get_post_format() );
  endwhile;
else :
  get_template_part( 'content', 'none' );
endif;

The trick is using the modulus operator (%), which gives you the remainder after dividing by a number (think back to elementary school).

You need to set a counter variable ($counter = 1) and increment it by one after each post ($counter++). Wherever the remainder is equal to 0, we display our custom code. Otherwise, display the regular post.

In this example, I’m inserting some code for every 4th post:

php
if ( $counter % 4 == 0 ):
  // your ad code here
else:
  // regular post
endif;
?>

Now with everything together:

php
if ( have_posts() ) :
  $counter = 1; //initialize the counter
  while ( have_posts() ) : the_post();
    if ( $counter % 4 == 0 ):
        // your ad code here
    else:
       get_template_part( 'content', get_post_format() );
    endif;

    $counter++; //increment by 1
  endwhile;
...
endif;
?>

Every theme is different, so don’t copy and paste this code directly into your theme file.

Leave a Reply