Echo a shortcode div after every 3 posts

First, let’s clean up this tag SPAM nightmare so we can read it and then simplify the code:

function adinserter() {
  return 'abcdefg';
}

if (have_posts()) { 
  $count = 0; 
  while (have_posts()) { 
    the_post(); 
    $count++; 
    get_template_part( 'content', get_post_format() ); 
    if ($count == 3) { 
      if (function_exists ('adinserter')) {
        echo adinserter (1); 
      }
      $count = 0; 
    }
  } 
}

You were duplicating code by having get_template_part() inside and else conditional and also inside the if itself. That code runs all the time. It doesn’t need to be in a conditional at all.

Next, your code works except for the placement of the echo function. Placing that before get_template_part() made the first add come out between posts #2 and #3– which is what I assume you mean by the code being inserted “at random positions”. The rest dropped in correctly. The way you had the if/else written this may have been hard to spot, but as soon as I cleaned that up the answer was fairly obvious.

So far, not much WordPress to it. The WordPress is this: you don’t need the counter. There is one built into the Loop. It is provided for you.

if (have_posts()) { 
  while (have_posts()) { 
    the_post(); 
    get_template_part( 'content', get_post_format() ); 
    if ($wp_query->current_post !== 0 && ($wp_query->current_post+1)%3 == 0) { 
      if (function_exists ('adinserter')) {
        echo adinserter (1); 
      }
    }
  } 
}

As far as why it doesn’t work with your infinite scroll, I can’t say as I don’t know how your infinite scroll works.

tech