Show In article ads every x amount of words repeatedly?

Viewed 69

I have a code that shows in-article ads after a specified amount of words, the thing is: If I write a very long article, the ad will be lost due to text length, so there will be only text showing. What I need to do is to create 1 or 2 ads and make it/them repeat indefinitely every 4 paragraphs and 250 words (just an example), based on article length.

HERE'S AN EXAMPLE:

This blog has the very same thing that I'm trying to achieve. As you scroll the article, you'll see that more and more ads will be loaded between the article paragraphs.

THIS IS MY CURRENT CODE:

// Insert ads after a number of words and after the </p> closing tag.
// https://stackoverflow.com/questions/42801541/insert-text-in-content-after-300-words-but-after-closing-tag-of-a-paragraph

function anunciamentosegundo($content) {
     $ad_code = '<script type="application/javascript">Adsense code goes here</script>';
    
    // only inject google ads if post is longer than 800 characters
    $enable_length1 = 1800;
    // Insert at the end of the paragraph every 200 words
    $after_word1 = 400;
    // Maximum of 2 ads
    $max_ads = 2;
    if (strlen($content) > $enable_length1) {
        $len = strlen($content);
        $i=0;
        // Keep adding untill end of content or $max_ads number of ads has ben inserted
        while($i<$len && $max_ads-->0) {
            // Work our way untill the apropriate length
            $word_cout = 0;
            $in_tag = false;
            while(++$i < $len && $word_cout < $after_word1) {
                if(!$in_tag && ctype_space($content[$i])) {
                    // Whitespace
                    $word_cout++;
                }
                else if(!$in_tag && $content[$i] == '<') {
                    // Begin tag
                    $in_tag = true;
                    $word_cout++;
                }
                else if($in_tag && $content[$i] == '>') {
                    // End tag
                    $in_tag = false;
                }
            }
            // Find the next '</p>'
            $i = strpos($content, "</p>", $i);
            if($i === false) {
                // No more paragraph endings
                break;
            }
            else {
                // Add the length of </p>
                $i += 4;
                // Get ad as string
          ob_start();
          echo $ad_code ; //would normally get printed to the screen/output to browser
          $ad = ob_get_contents();
          ob_end_clean();
                $content = substr($content, 0, $i) . $ad . substr($content, $i);

                // Set the correct i
                $i+= strlen($ad);
            }
        }
    }
    return $content;
}
add_filter( 'the_content', 'anunciamentosegundo' );

Currently I can show ads after an amount of words and paragraphs, but not every x amount words and paragraphs. What should I do?

0 Answers
Related