A good Adsense injection function will place ads at the right places by taking into account word count without counting HTML markup and by prioritizing user experience.
Objective
In this post, I will walk you through the process of creating my best function for inserting Adsense code into WordPress posts.
The function will meet the following requirements:
- Inserts ads for posts, pages, custom post types, or all
- Inserts an ad after n-words without counting HTML markup
- Inserts ads after a paragraph’s closing tag
- Can be used in the_content hook or directly in a template.
- Its portable and simple.
<?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 > 4) { $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 4-word count happens to be at the end of the content, resulting in two ad placements at the end of the content.