Last active
September 29, 2019 09:55
-
-
Save 2shrestha22/3e8371e01128582148f542605aa92fbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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