• zvhipp

    (@zvhipp)


    Hello, I am trying to figure out how to put adsense between posts. I know how to put ads in between post. But codes I have found so far are allowing me to put 1 ad between any selected number of post. I have 6 posts per page, I want adsense after 2nd and 4th post.

    <?php $count = 1; ?>……
    <?php if ($count == 2) : ?>
    adsense code
    <?php endif; $count++; ?>

    above is good enough only for 1 block of ad. Any idea? Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Use modulo division to determine when to output an ad. $count % $b is equivalent to the remainder of $count divided by $b. $b is the frequency of ads, the remainder relates to how many posts are output before the first ad.

    Thread Starter zvhipp

    (@zvhipp)

    This code below is what I found and worked perfectly for ‘content’ single page. It will be helpful to others.

    add_filter('the_content', 'prefix_insert_post_ads');
    
    /**
     * Content Filter 
     */
    function prefix_insert_post_ads($content) {
    
        $insertion = 'Your Adsense Code Goes Here';
    
        if (is_single() && ! is_admin()) {
            return prefix_insert_after_paragraphs($content, $insertion, array(2,8));
        }
    
        return $content;
    
    }
    
    // Function that makes the magic happen correctly
    
    function prefix_insert_after_paragraphs($content, $insertion, $paragraph_indexes) {
    
        // find all paragraph ending offsets
    
        preg_match_all('#</p>#i', $content, $matches, PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
    
        // reduce matches to offset positions
    
        $matches = array_map(function($match) {
            return $match[0][1] + 4; // return string offset + length of </p> Tag
        }, $matches);
    
        // reverse sort indexes: plain text insertion just works nicely in reverse order
    
        rsort($paragraph_indexes); 
    
        // cycle through and insert on demand
    
        foreach ($paragraph_indexes as $paragraph_index) {
            if ($paragraph_index <= count($matches)) {
                $offset_position = $matches[$paragraph_index-1];
                $content = substr($content, 0, $offset_position) . $insertion . substr($content, $offset_position);
            }
        }
    
        return $content;
    
    }
    
    

    ($content, $insertion, array(2,8) – Here is where you can make the change – code here is set to show adsense after 2nd and 8th paragraph.

    • This reply was modified 7 years, 12 months ago by zvhipp.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Adsense Between Posts on Category Pages – Multiple’ is closed to new replies.