Skip to content

Instantly share code, notes, and snippets.

@galbaras
Last active November 22, 2017 01:55
Show Gist options
  • Save galbaras/100793bb2e3fe956fe00b1f7a5c535c0 to your computer and use it in GitHub Desktop.
Save galbaras/100793bb2e3fe956fe00b1f7a5c535c0 to your computer and use it in GitHub Desktop.
Insert Google ad after specific top-level text block in WordPress post
/*
* This code is for WordPress and should be used in functions.php of the active theme.
*
* Before using it, replace "ADVERTISER ID" with your own advertiser ID and "SLOT ID" with your own slot ID
* (you can get both in Google AdSense). For best results, use a reponsive ad unit.
*
* If your posts contain "pre", "noscript" or some other type of HTML block, add them to $block_tags.
*
* You can change the insertion point by changing $after_block.
*
* In English, there are 4.5 letters per word and 150 words per paragraph on average, which is 2025 for 3 paragraphs,
* so a post with 2000 is short and the ad will go to the end of it.
*
* Suggested styling for "ad-conttent-after-p3": 300px width, floated left, on wide displays, and full width, not floated,
* on narrow displays. The ad serving code will deliver ads that fit into the space provided on every device.
*/
add_filter( 'the_content', 'insert_ad', 999999 );
function insert_ad( $content ) {
if ( ! is_single() ) {
return $content;
}
$google_ad = '
<p class="ad-content-after-p3">
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ADVERTISER ID"
data-ad-slot="SLOT ID"
data-ad-format="auto">
</ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</p>
';
$block_tags = array( 'p' => 1, 'blockquote' => 10, 'table' => 5, 'ul' => 2, 'ol' => 2, 'div' => 3, 'dl' => 2, 'h2' => 2, 'h3' => 2, 'h4' => 2 );
$after_block = 3;
$start = 0;
for ( $block = 0; $block < $after_block; $block++ ) {
$start = stripos( $content, '<', $start ); // Find the start of the next block
$closing_tag = '</p>'; // Fallback
foreach ( $block_tags as $tag => $length ) {
if ( strtolower( substr( $content, $start+1, $length ) ) == $tag ) {
$closing_tag = "</$tag>";
break;
}
}
$end = stripos( $content, $closing_tag, $start );
if ( $end !== false ) {
$end += strlen( $closing_tag );
$start = $end + 1;
}
}
if ( $start < 2000 ) { // Nothing found or content too short - show ad after content
return $content . $google_ad;
}
// Insert ad after 3rd block
return substr( $content, 0, $start-1 ) . $google_ad . substr( $content, $start );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment