Created
October 13, 2021 03:34
-
-
Save permanart/d6453d75e65f3f575c2cd70ea0750ce4 to your computer and use it in GitHub Desktop.
Show multiple ads within paragraph wordpress
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
//Insert ads after n paragraph multiple ads | |
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?client=ca-pub-5327211893729632" | |
crossorigin="anonymous"></script> | |
<ins class="adsbygoogle" | |
style="display:block; text-align:center;" | |
data-ad-layout="in-article" | |
data-ad-format="fluid" | |
data-ad-client="ca-pub-xxxxxxxxxxxxxxx" | |
data-ad-slot="xxxxxxxxxxxxx"></ins> | |
<script> | |
(adsbygoogle = window.adsbygoogle || []).push({}); | |
</script>'; | |
$ad_code2 = $ad_code; //you can add more adsense code here | |
if ( is_single() && ! is_admin() ) { | |
//you can add multiple condition here | |
$content = prefix_insert_after_paragraph( $ad_code1, 3, $content ); | |
$content = prefix_insert_after_paragraph( $ad_code2, 6, $content ); | |
$content = prefix_insert_after_paragraph( $ad_code1, 9, $content ); | |
$content = prefix_insert_after_paragraph( $ad_code1, 12, $content ); | |
return $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 ( $paragraph_id == $index + 1 ) { | |
$paragraphs[$index] .= $insertion; | |
} | |
} | |
return implode( '', $paragraphs ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment