<?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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment