Support » Developing with WordPress » How to insert code/adverts on index.php after 6 posts

  • ispreview

    (@ispreview)


    At present I can insert some advertising code after 3 paragraphs into a single article (single.php) by simply adding this to my functions.php file:

    add_filter ( 'the_content', 'prefix_insert_post_ads' );
    function prefix_insert_post_ads( $content ){
    	$ad_code = 'the HTML code goes here';
    
    	if ( is_single() && ! is_admin() ) {
    		return prefix_insert_after_paragraph( $ad_code, 3,$content );
    	}
    	return $content;
    }

    However what I’d also like to do, without using a plugin that will add lots of stuff I don’t need or want (extra java in the headers etc.), is on my index.php add some extra code/advert between my summary of latest news posts. Maybe after every 6 posts, so the advert would display between the 6th and 7th latest post summary on my index.php.

    So somehow I need to add a function (functions.php) to inject the extra CSS/Ad code and manipulate <?php if(have_posts()) : ?><?php while(have_posts()) : the_post(); ?> but I don’t know how?

    • This topic was modified 1 year ago by ispreview.
    • This topic was modified 1 year ago by ispreview.
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    As you probably know, all code between while( have_posts()): and endwhile; is “The Loop” and generates what appears for every post. You’ve probably also figured out that adding code within the loop will cause related output on every post in the list. Exactly where in the loop relative to other code determines where in each post your ad will display.

    In order to only output an ad on every 6th post, you need a counter to keep track of how many posts have been output. The counter needs to be initialized outside of the loop, before it is entered: $count = 0;

    Just before the endwhile; statement, increment the counter: $count ++;

    Then divide the count by 6 inside a conditional statement and only output the ad when the division remainder is equivalent to some value. The remainder value sought (the 0 below) controls where in the list the ad first appears.

    if ( 0 == $count % 6 ) { ?>
      <div>You ad HTML goes here.</div>
    <?php }

    The % operator is the modulo operator which returns the remainder of integer division, division by 6 in this case. (for example, 15 % 6 returns 3) This code goes within the loop where ever in the post you want ads to appear. You will not be able to place ads within post content this way, only before or after any complete post element.

Viewing 1 replies (of 1 total)
  • The topic ‘How to insert code/adverts on index.php after 6 posts’ is closed to new replies.