Created
September 29, 2019 09:59
-
-
Save 2shrestha22/eb0b9cc9221dde12dd323604b5720e1e 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
<?php | |
//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>'; | |
if ( is_single() ) { | |
return prefix_insert_after_paragraph( $ad_code1, 3, $content ); | |
} | |
return $content; | |
} | |
// Parent Function that makes the magic happen | |
function prefix_insert_after_paragraph( $insertion1, $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; | |
} | |
} | |
return implode( '', $paragraphs ); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment