Forum Moderators: martinibuster
add_filter('the_content', 'prefix_insert_post_ads');
function prefix_insert_post_ads($content) {
$insertion = 'put your adsense code here';
if (is_single() && ! is_admin()) {
return prefix_insert_after_paragraphs($content, $insertion, array(3));
}
return $content;
}
function prefix_insert_after_paragraphs($content, $insertion, $paragraph_indexes) {
preg_match_all('#</p>#i', $content, $matches, PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
$matches = array_map(function($match) {
return $match[0][1] + 4; // return string offset + length of </p> Tag
}, $matches);
rsort($paragraph_indexes);
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;
}