Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//adding adsense ad unit inside the article
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code1 = '<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- inContent -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxxxx"
data-ad-slot="xxxxxxxxxxx"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><p></p>';
$ad_code2 = '<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- inContent -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxxxx"
data-ad-slot="xxxxxxxxxxx"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><p></p>';
if ( is_single() ) {
return prefix_insert_after_paragraph( $ad_code1, $ad_code2, 3, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion1, $insertion2, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion1;
}
//added by me
if ( $paragraph_id == $index - 3 ) {
$paragraphs[$index] .= $insertion2;
}
if ( $paragraph_id == $index - 7 ) {
$paragraphs[$index] .= $insertion1;
}
}
return implode( '', $paragraphs );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.