Last active
October 13, 2021 04:09
-
-
Save 2shrestha22/c4a5c1ae9fffa73dbe2aa4b4089577ce 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 | |
//-------------------------------------------------------------- | |
//-------------------------------------------------------------- | |
//---------COPY CODE BELOW THIS LINE---------------------------- | |
//Adding adsense ad unit inside the article | |
//Insert ads after every third paragraph of single post content. | |
add_filter( 'the_content', 'prefix_insert_post_ads' ); | |
function prefix_insert_post_ads( $content ) { | |
//CHANGE BELOW AdSense CODE WITH YOUR OWN CODE | |
$ad_code = ' | |
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> | |
<!-- inContent --> | |
<ins class="adsbygoogle" | |
style="display:block" | |
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" | |
data-ad-slot="xxxxxxxxxx" | |
data-ad-format="auto" | |
data-full-width-responsive="true"></ins> | |
<script> | |
(adsbygoogle = window.adsbygoogle || []).push({}); | |
</script> | |
<p></p> | |
'; | |
if ( is_single() ) { | |
//CHANGE 3 TO DESIRED NUMBER YOU WANT ADVERT TO BE APPEARED | |
return prefix_insert_after_paragraph( $ad_code, 3, $content ); | |
} | |
return $content; | |
} | |
// Parent Function that makes the magic happen | |
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { | |
$closing_p = '</p>'; | |
$paragraphs = explode( $closing_p, $content ); | |
foreach ($paragraphs as $index => $paragraph) { | |
if ( trim( $paragraph ) ) { | |
$paragraphs[$index] .= $closing_p; | |
} | |
if ( ( ($index + 1) % $paragraph_id ) == 0 ) { | |
$paragraphs[$index] .= $insertion; | |
} | |
} | |
return implode( '', $paragraphs ); | |
} | |
Hi! Is possible to modify the code to have 3 ads code instead of one?
Refer to this code
https://gist.github.com/permanart/d6453d75e65f3f575c2cd70ea0750ce4
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi! Is possible to modify the code to have 3 ads code instead of one?