Categories
AMP On WordPress Experiments Web Development Wordpress

AMP for WordPress Easily Adding Flying Carpet Adsense Ads

Recently during browsing on my phone, I came across, flying carpet ads on a news site and it was an awesome effect when it comes to displaying ads, name it flying carpet on the AMP or Parallax effect traditionally.

As I am using a Standard AMP Mode, I thought of giving this a try and luckily this worked, this is how it looked on a big screen in the screen cast below

flying carpet ads

Now the problem was pushing this to each and every post on my blog and exactly near the second paragraph, so here is what I did simply adding a function to the functions.php file of my twenty twenty theme ( child theme ).

//Insert flying carpets ads after second paragraph of single post content.

add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
 $ad_code = '<amp-fx-flying-carpet height="320">
<amp-ad width="100vw" height="320" type="adsense" data-ad-client="ca-pub-1234567891000000" data-ad-slot="098654321" data-auto-format="rspv" data-full-width="">
  <div overflow=""></div>
</amp-ad>
</amp-fx-flying-carpet>';
 if ( is_single() && ! is_admin() ) {
 return prefix_insert_after_paragraph( $ad_code, 2, $content );
 }
return $content;
}
// Function to get this done
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 );
}

Make sure to change with your AdSense Code, for a live example how it looks you can see that on any post of this blog,

Still, if you have problems in displaying AdSense on AMP for WordPress I have written a detailed post here about AdSense Auto Ads Amp WordPress.

In almost all my posts for AMP on WP, I have all words for Appreciation but only for the Original AMP Plugin that I use and always recommend.

By Rahul Kharbanda

Hi,
I am Rahul Kharbanda from India. I hope you like all the content I made. Welcome to comment & connect.
I am on Quora , Github , Twitter

Leave a Reply