Another WordPress Development Blog

Automatically insert Adsense code in old posts.


There are many situations when old blogs with tons of posts and traffic are not monetized at all. At one point the owner may decide to publish ads(or some other commercial stuff) inside posts. But how ? Editing 300+ posts to manually insert ads is not really a solution if you are an individual.

Here is a quick solution. The code below will take your posts, split them by ‘<p>’ tags (paragraphs) and insert a code every x(a number you can change) paragraphs.

Copy paste the code in your functions.php and replace the $commercial value with your ad code .I promise I will make a plugin that will do this but in a friendly manner.

add_filter('the_content', 'display_autoadsense');

function display_autoadsense($content){

$commercial=' --->> Copy paste here the adsense code << ---';
$needle='</p>';
$bum=explode($needle,$content);
$count=0;
$every=3;

foreach ($bum as $key => $value) {
$count++;
if($count ===$every){
$new_content= $new_content.$value.'</p><p>'.$commercial.'</p>';
$count=0;
}

else {
$new_content= $new_content.$value.'</p>';
}

}

return $new_content;
}

Change the value of $every with the no of paragraphs you want between ads. Remove the $ count=0; line if you want to display ads only one time.

Random Posts

Leave a Reply