Brogramo
<span class='guest_name'>Guest</span>Guest

Simple Function to Add Adsense Code in WordPress Post

I have had many attempts at developing an effective function for inserting Adsense code in my blog posts that makes sense for my situation. The function below meets the following requirements:

  1. The function inserts ads for posts and not pages
  2. The function does not insert ads if the content is empty
  3. The function inserts an ad after 400 words, immediately after the end of the paragraph

In conjunction with the function below, I manually insert an ad after the title of the post and the function does the rest of the work.

<?php
add_action('the_content', function($content) { 
    if (!is_single()) {         
       return $content; 
    }
    if(!$content) {     
       return $content; 
    } 
    $chunks = explode('</p>', $content); 
    $counter = 0; 
    for($i = 0; $i < count($chunks); $i++) {     
        $counter += str_word_count(strip_tags($chunks[$i]));     
        if( $counter > 400) {         
            $chunks[$i] .= ARTICLE_AD;         
            $counter = 0;     
        } 
    }     
    return implode("", $chunks); 
});

If you would also like to insert an ad at the end of the content then I have a different version of the function to account for situations where the 400-word count happens to be at the end of the content, resulting in two ads being placed at the end of the content. If you want to see this version, send me a suggestion.