Skip to content

Instantly share code, notes, and snippets.

@CapWebSolutions
Created November 9, 2017 15:37
Show Gist options
  • Select an option

  • Save CapWebSolutions/5ae44b71402aa35d4c1621a264ea3dc7 to your computer and use it in GitHub Desktop.

Select an option

Save CapWebSolutions/5ae44b71402aa35d4c1621a264ea3dc7 to your computer and use it in GitHub Desktop.
nsert ads after second paragraph of single post content.
<?php
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'wsm_insert_post_ads' );
function wsm_insert_post_ads( $content ) {
$ad_code = '<div class="content-ad-block"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Top Posts 300 250 -->
<ins class="adsbygoogle"
style="display:inline-block;width:300px;height:250px"
data-ad-client="ca-pub-2169025261524250"
data-ad-slot="4828803481"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>';
if ( is_single() && ! is_admin() ) {
return wsm_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function wsm_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 );
}
@CapWebSolutions
Copy link
Copy Markdown
Author

Borrowed from https://www.careerpointkenya.co.ke/ method of ad insertion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment