Created
September 19, 2016 15:14
-
-
Save isaumya/578149ae19b140377fe0f6d348b1b163 to your computer and use it in GitHub Desktop.
Insert AdSense Ad code after certain paragraph number. Please note that the following code will consider all `p` tags into its consideration while executing
This file contains hidden or 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 | |
/* | |
Plugin Name: Insert AdSense Ad Code after certain paragraph | |
Plugin URI: https://www.isaumya.com/ | |
Description: Insert AdSense Ad code after certain paragraph number considering all `p` tags | |
Version: 1.0 | |
Author: Saumya Majumder | |
Author URI: https://www.isaumya.com/ | |
*/ | |
//* Ad below the 1st paragraph of post | |
add_filter( 'the_content', function( $content ) { | |
$paragraphNumber = 1; | |
$ad_code = '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> | |
<!-- Responsive Ad Code --> | |
<ins class="adsbygoogle center top-ad" | |
style="display:block" | |
data-ad-client="ca-pub-XXXXXXXXXXXX" | |
data-ad-slot="XXXXXXXXXXXXX"></ins> | |
<script> | |
(adsbygoogle = window.adsbygoogle || []).push({}); | |
</script>'; | |
//Check if this is an AMP page then push the AMP page specific ad code | |
if ( function_exists( 'is_amp_endpoint' ) ) { | |
if( is_singular( 'post' ) && is_amp_endpoint() ) { | |
$ad_code = '<!-- AMP Ad Code --> | |
<div class="adsbygoogle"> | |
<amp-ad width=300 height=250 | |
type="adsense" | |
data-ad-client="ca-pub-XXXXXXXXXXXX" | |
data-ad-slot="XXXXXXXXXXXXX"></amp-ad> | |
</div>'; | |
return ad_insert_after_paragraph( $ad_code, $paragraphNumber, $content ); | |
} | |
} | |
if ( is_singular( 'post' ) ) { | |
return ad_insert_after_paragraph( $ad_code, $paragraphNumber, $content ); | |
} | |
return $content; | |
}, 19); | |
// Parent Function that makes the magic happen | |
function ad_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