wordpresswordpress-themingcustom-wordpress-pages

I need a function that after three posts give me my add then after four posts give my add fifth then


I need a function that after three posts give me my add then after four posts give my add fifth then after eight posts give new my add then a big banner in the middle then again the same scene the same series starts. Go to the loop and then down to the pagination ETC...

Post1   Post2   Image
Post4   Post5   Post6
Image   Post8   Post9
Post10   Post11   Post12
Post13   Post14   Image

Big Image

Post16   Post17   Image
Post19   Post20   Post21
Image   Post23   Post24

Pagination 1 2 3 4 5 ....

Like this Help Me enter image description here


Solution

  • You'll need to add code to the loop in your theme. If this is your home page, then you would edit the loop in index.php. If it's a category page or you want it to apply to those pages too, you'll edit the loop in archive.php (assuming you don't have a template file targeting categories, in which case you'd edit it there as well).

    The start of the loop will look something like (or exactly) like this:

    <?php if (have_posts()): while (have_posts()) : the_post(); ?>
    

    Before this line, add an array containing the HTML for your ads, like this:

    <?php 
      $ads = [
        '<div class="post-ad"><a href="enter-url-here"><img src="ad-image-here" /></a></div>',
        '<div class="post-ad"><a href="enter-url-here"><img src="ad-image-here" /></a></div>',
        '<div class="post-ad"><a href="enter-url-here"><img src="ad-image-here" /></a></div>',
        // and so on
      ];
    ?>
    

    Also before the loop starts, add a counter variable and an array of the positions you want the ads to show in:

    <?php 
      $count = 0; 
      $ad_positions = [3, 7, 11, 15]; // enter the desired positions
    ?>
    

    Inside the loop, add this code that increments the counter variable, and outputs ads based on the counter variable:

    <?php
      $count++;
      if( in_array( $count, $ad_positions ) ){
        $ad = array_shift( $ads ); // gets and removes the first ad from the array
        echo $ad;
        
      } 
    ?>
    

    So your while loop will be this (now that I have that code to look at:

    while ( have_posts() ) :
      the_post();
                    
      $count++;
      if( in_array( $count, $ad_positions ) ){
        $ad = array_shift( $ads ); // gets and removes the first ad from the array
        echo $ad;
        $count++;  // the ad takes up a position, so this will make the next one appear in the right place.
      }
      get_template_part( $template ); 
    endwhile;