Web & Software Developer

Add Google Adsense To WordPress AMP Plugin (Accelerated Mobile Pages)

This shows you how to add Google Adsense to your Accelerated Mobile Pages (AMP) if you’re using the WordPress AMP plugin by Automattic.

This page offers four different ways to add Google Adsense to AMP.

  1. The first example will add Adsense to your AMP pages, above the content.
  2. The second example will add Google Adsense above the content, and also within the content after a certain number of paragraphs.
  3. The third example will add Adsense within the content after a certain number of paragraphs.
  4. The fourth example is completely different. It creates one shortcode that works on both regular and AMP (Accelerated Mobile Pages) to display your Google Adsense ads.

Examples 2 and 3 are useful if you want to automatically insert an ad in between paragraphs (after a specified number of paragraphs) in your AMP post content. However, example 4 gives you complete control of where to display your ads within your content.

All four of these examples will make Google Adsense work on WordPress AMP pages if you use the WordPress AMP plugin by Automattic.

Mandatory Step 1:

First, you will need a “responsive” Google Adsense ad unit. If you don’t have one already, then create a new ad unit like this:

  • Log in to your Google Adsense account –> click “Ad Units” –> click “New ad unit” –> select “Text & display ads.”
  • Give the new ad unit a name like “AMP ad for My Site.”
  • For Ad size, you must select the Responsive one.
  • Click “Save and get code.” Note down the following information from your responsive ad code:
    • Your publisher ID (data-ad-client), for example, ca-pub-1234567891234567.
    • Your ad unit’s ID (data-ad-slot), for example, 1234567890.

    You’ll need to paste these two values in the examples below.

 

Mandatory Step 2:

Also, whether you use Example 1, Example 2, Example 3, or Example 4, either way, you must add the AMP Ad .js script to add support for the amp-ad element. This is easy to do. Add the AMP Ad script to your WordPress site by adding this to your functions (see how to add code):

/**
 * Add the AMP Ad script to AMP pages.
 */
function isa_load_amp_adsense_script( $data ) {
    $data['amp_component_scripts']['amp-ad'] = 'https://cdn.ampproject.org/v0/amp-ad-0.1.js';
    return $data;
}
add_filter( 'amp_post_template_data', 'isa_load_amp_adsense_script' );

 

Now you are ready to move on to the examples for adding the actual Adsense code. Here are the 4 examples.

Example 1: Add Google Adsense To AMP, Above The Content

Note that this method adds the Adsense above the AMP post content, but below the featured image. (If there is no featured image, then the ad will simply be above the content.)

To add Google Adsense to the top of WordPress AMP content, just add the following code to your functions. However, you must edit line 12 to replace “ca-pub-1234567891234567” with your own publisher ID. Edit line 14 to replace “1234567890” with your own ad unit’s ID.

/**
 * Add Google Adsense code to AMP above the content
 */
add_action( 'pre_amp_render_post', 'isa_amp_add_content_filter' );

function isa_amp_add_content_filter() {
	add_filter( 'the_content', 'isa_amp_adsense_above_content' );
}

function isa_amp_adsense_above_content( $content ) {

	$publisher_id = 'ca-pub-1234567891234567';

	$ad_slot = '1234567890';

	// Add Adsense ad above AMP content
	$ad_code = '<amp-ad layout="fixed-height" height="100" type="adsense" data-ad-client="' . $publisher_id . '" data-ad-slot="' . $ad_slot . '"></amp-ad>';

	return $ad_code . $content;
}


See the note below about previewing your ads on AMP pages.

Top

Example 2: Add Google Adsense To AMP, Above and Within The Content

This example will add an Adsense ad above the content, and another Adsense ad within the content, after the second paragraph. If you want to display the ad after a later paragraph, instead of the second paragraph, change the “2” on line 25, below, to the number of your desired paragraph. However, if a post does not have that number of paragraph, then no ad will be shown at that spot. (The ad above the content will still be shown.)

You must edit the following code on lines 12 and 14. You must edit line 12 to replace “ca-pub-1234567891234567” with your own publisher ID. Edit line 14 to replace “1234567890” with your own ad unit’s ID.

/**
 * Add Google Adsense code to AMP above the content, and within the content
 */
add_action( 'pre_amp_render_post', 'isa_amp_add_content_filter' );

function isa_amp_add_content_filter() {
	add_filter( 'the_content', 'isa_amp_adsense_above_within_content' );
}

function isa_amp_adsense_above_within_content( $content ) {

	$publisher_id = 'ca-pub-1234567891234567';

	$ad_slot = '1234567890';

	$ad_code_end = ' type="adsense" data-ad-client="' . $publisher_id . '" data-ad-slot="' . $ad_slot . '"></amp-ad>';

	// Above the fold ad code. This is fixed height as per Google guidelines for Adsense for AMP.
	$atf_ad_code = '<amp-ad layout="fixed-height" height="100"' . $ad_code_end;

	// Below the fold ad code. This is responsive as per Google guidelines for Adsense for AMP.
	$btf_ad_code = '<amp-ad layout="responsive" width="300" height="250"' . $ad_code_end;

	// Insert Adsense ad between the content, after paragraph 2
	$new_content = isa_insert_after_paragraph( $btf_ad_code, 2, $content );

	// Insert Adsense ad above AMP content
	return $atf_ad_code . $new_content;

}
function isa_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 );
}

See the note below about previewing your ads on AMP pages.

Top

Example 3: Add Google Adsense To AMP Within The Content

This example adds the Google Adsense to your AMP posts within the content, but not above the content. This will add Adsense after the second paragraph. If you want to display the ad after a later paragraph, instead of the second paragraph, change the “2” on line 20, below, to the number of your desired paragraph. However, if a post does not have that number of paragraph, then no ad will be shown at that spot.

You must edit the following code on lines 12 and 14. You must edit line 12 to replace “ca-pub-1234567891234567” with your own publisher ID. Edit line 14 to replace “1234567890” with your own ad unit’s ID.

/**
 * Add Google Adsense code to AMP within the content, but <strong>not</strong> above.
 */
add_action( 'pre_amp_render_post', 'isa_amp_add_content_filter_within' );

function isa_amp_add_content_filter_within() {
	add_filter( 'the_content', 'isa_amp_adsense_within_content' );
}

function isa_amp_adsense_within_content( $content ) {

	$publisher_id = 'ca-pub-1234567891234567';

	$ad_slot = '1234567890';

	// Below the fold ad code. This is responsive as per Google guidelines for Adsense for AMP.
	$btf_ad_code = '<amp-ad layout="responsive" width="300" height="250" type="adsense" data-ad-client="' . $publisher_id . '" data-ad-slot="' . $ad_slot . '"></amp-ad>';

	// Insert Adsense ad between the content, after paragraph 2
	$new_content = isa_insert_after_paragraph( $btf_ad_code, 2, $content );

	return $new_content;

}
function isa_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 );
}

See the note below about previewing your ads on AMP pages.

Top

Example 4: Display Google Adsense With A Shortcode That Works on Regular and AMP Pages

Google Adsense WordPress Shortcode That Works on Regular and Accelerated Mobile Pages

Here, I show you a completely different way to add Google Adsense to your WordPress Accelerated Mobile Pages. This way is different from the previous examples in 2 ways:

  1. This shows you how to add Google Adsense with a shortcode. This way gives you complete control of where to display your ads within your content. You place the shortcode in your content where you want the ads to be shown. (Whereas the previous examples show how to insert ads automatically after a certain number of paragraphs.)
  2. This shortcode will make Google Adsense ads appear on both regular posts and AMP posts (Accelerated Mobile Pages). The shortcode detects if an AMP page is being viewed, and if so, then it will use the AMP-compatible ad code. If the page is not an AMP page, then it will use the regular ad code. So, this shortcode ensures that your Google Adsense will work on both regular posts and AMP pages (Accelerated Mobile Pages).

To create the shortcode, add the following code to your functions. But first, you must edit line 6 to replace ca-pub-1234567891234567 with your own publisher ID. Edit line 8 to replace 1234567890 with your own ad unit’s ID.

/**
 * Shortcode To Display Google Adsense ads on regular posts and and AMP (Accelerated Mobile Pages)
 */
function isa_get_amp_and_regular_adsense( $atts ) {

    $publisher_id = 'ca-pub-1234567891234567';
 
    $ad_slot = '1234567890';
 
	if ( is_amp_endpoint() ) {
		return '<amp-ad layout="responsive" width="300" height="250" type="adsense" data-ad-client="' . $publisher_id . '" data-ad-slot="' . $ad_slot . '"></amp-ad>';
	} else {
		return '<ins class="adsbygoogle" style="display:block" data-ad-client="' . $publisher_id . '" data-ad-slot="' . $ad_slot . '" data-ad-format="auto"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script>';
	}
}
add_shortcode( 'isa_amp_and_regular_adsense', 'isa_get_amp_and_regular_adsense' );

/**
 * Add the regular Adsense script to regular single posts.
 */
function isa_load_regular_adsense_script() {
    wp_register_script( 'google-adsense', '//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', '', null, true );
    if ( is_single() ) {
    	wp_enqueue_script( 'google-adsense' );
    }
}
add_action( 'wp_enqueue_scripts', 'isa_load_regular_adsense_script' );

/**
 * Add async attribute to the regular Adsense script.
 */
function isa_adsense_async_script( $tag, $handle, $src ) {
    if ( 'google-adsense' == $handle ) {
        return '<script async src="' . $src . '"></script>';
    }
    return $tag;
}
add_filter( 'script_loader_tag', 'isa_adsense_async_script', 10, 3 );

The code above takes care to load the necessary AMP ad script to AMP pages, and the regular Adsense script (adsbygoogle.js) on regular single posts.

Shortcode Usage

The shortcode looks like this:

[isa_amp_and_regular_adsense]

To use the shortcode, paste it within your post content where you want the ads to be displayed. You would use this inside your WordPress dashboard, when you’re creating or editing a post. So, in the post editor, paste the shortcode somewhere within the post content. Remember that Google Adsense has a limit of 3 regular ads per page.

Note: If you want to preview how your ads will appear on your AMP pages (Accelerated Mobile Pages), you should navigate to one of your AMP URLs on a mobile device (like a cell phone). If you preview your AMP page in a regular desktop browser, you will probably not see the ads. This is okay because AMP pages will only be shown to users on mobile devices, hence the name “Accelerated Mobile Pages.”

Top

By

We've 27 Responses

  1. February 19th, 2017 at 3:02 am

    Thank you for the best series of articles on how to customize AMP in wordpress. This adsense bit is particularly important, since noone wants to lose on mobile monetization.

    Got a question though: how can you show an add after the 3rd paragraph ?

    Thanks a lot!
    Corina

    avatar
    • February 19th, 2017 at 9:19 am

      Thank you. To show an ad after the 3rd paragraph, use Example 3 and make this change:

      On line 20, change the number 2 to a 3.

      I just updated the description to make it a bit more clear.

      avatar
  2. February 26th, 2017 at 3:35 pm

    Thanks.

    One more thing please, is there a way of increasing the white space around the ads?

    So I added ins.adsbygoogle { margin: 50px auto; } to style.php but it didn’t work

    avatar
    • April 3rd, 2017 at 7:16 pm

      Yes, sorry I didn’t mention that. To target the ads on the AMP pages, it’s amp-ad instead of ins.adsbygoogle. And, instead of inserting it into the single.php, you can add the following code to your functions. This will insert CSS into the AMP pages. You can add as many custom CSS styles as you wish into line 5:

      add_action( 'amp_post_template_css', 'my_amp_css_styles' );
      function my_amp_css_styles( $amp_template ) {
      	?>
      	amp-ad { margin: 30px auto; }
      
      	<?php
      }
      

      This adds top and bottom margins of 30 pixels. You can change 30 to your desired height for the top and bottom margins.

      avatar
    • March 8th, 2017 at 10:24 pm

      If you only want the ad at the end of the content, use Example 1, but change line 19 to this:

      return $content . $ad_code;

      That will put the the ad after the content. Hope that helps.

      avatar
  3. March 13th, 2017 at 10:51 pm

    Thanks a lot for your articles about AMP in wordpress. They are helping me a lot! =)

    I’ve just implemented the adsense in my site. But I’d like to know if it is possible to implement the Matched Content Unit from google adsense? Any idea?

    avatar
  4. March 15th, 2017 at 2:45 am

    Good day ma,

    Please by any chance do you have this tutorial for non-amp pages? That is if I want to do the Google Adsense Within The Content thing on my regular desktop theme.

    Thanks

    avatar
  5. March 28th, 2017 at 10:42 am

    Hi

    I managed to add ads above the content and after paragraph 2. Now, can you help me with below two problem

    a) How to show ad at the bottom of the website or at the end of the article
    b) How to add more than one ad slot. I want to show link text ad beneath the image ad.
    Is this possible with your code

    Please help

    avatar
    • April 3rd, 2017 at 7:38 pm

      If you’re using Example 2 to add ads above the content and after paragraph 2, then you can modify that to solve both of these problems. This modification will also add an ad after the content. It will also add a second ad slot that will be shown after every ad.

      In Example 2, replace lines 10–30 with the following. The first ad unit ID goes on line 5, and the second ad unit ID goes on line 7. Also replace the publisher ID with your own on line 3.

      function isa_amp_adsense_above_within_content( $content ) {
       
          $publisher_id = 'ca-pub-1234567891234567';
       
          $ad_slot = '1234567890';
      
          $ad_slot_2 = '2222222222';
       
          $ad_code_end = ' type="adsense" data-ad-client="' . $publisher_id . '" data-ad-slot="' . $ad_slot . '"></amp-ad>';
      
          $ad_code_end_2 = ' type="adsense" data-ad-client="' . $publisher_id . '" data-ad-slot="' . $ad_slot_2 . '"></amp-ad>';
       
          // Above the fold ad code. This is fixed height as per Google guidelines for Adsense for AMP.
          $atf_ad_code = '<amp-ad layout="fixed-height" height="100"' . $ad_code_end . '<amp-ad layout="fixed-height" height="100"' . $ad_code_end_2;
      
          // Below the fold ad code. This is responsive as per Google guidelines for Adsense for AMP.
          $btf_ad_code = '<amp-ad layout="responsive" width="300" height="250"' . $ad_code_end . '<amp-ad layout="responsive" width="300" height="250"' . $ad_code_en_2d;
       
          // Insert Adsense ad between the content, after paragraph 2
          $new_content = isa_insert_after_paragraph( $btf_ad_code, 2, $content );
       
          // Insert Adsense ad above AMP content
          return $atf_ad_code . $new_content . $btf_ad_code;
       
      }
      
      avatar
  6. April 19th, 2017 at 3:03 am

    Dear Isable,

    This guide has been my life save. I want to draw your attention to Google’s Adsense Guideline – specially on Above the Fold. My question is how to add google’s advised 320 x 100 Add unit instead of your fixed height of 100? See Here (https://support.google.com/adsense/answer/6357180) They said:

    Place a 320×100 ad unit above the fold

    By choosing the 320×100 ad unit, you allow 320×50 display ads to compete to appear as well, which could lead to higher RPMs. Placing these large mobile banners on your site could also boost your earnings through increased click rates.

    We recommend that you place your 320×100 ad unit above the fold. Our research shows that the most valuable ad position is right above the fold.

    In example 2 and line no 19, I just changed your mentioned code into this. Is it OK?

    <amp-ad layout="responsive" width="320" height="100"' . $ad_code_end;
    avatar
    • April 19th, 2017 at 3:21 am

      I want to add one more point which many adsense publishers may find useful. I am using code of Example 2 which is brilliant since I can automatically add code within my post and after my desirable paragraph. But sites like mine which has 200+ articles and where sometimes I have added images in central position of paragraph 1 and sometimes after paragraph 2 in that case this code may create little bit problem. Ad may appear right after image which may create problem. Is there anyway to stop showing ads after image or should I use more extra space before and after ads. If 2nd one is the solution then how to do that?

      Also please let me know, to remain on the safer side, how to put a horizontal line above and after ad code. I am meaning HTML hr tag . Please let me know how can I put light color horizontal line above and below the code to remain in the safest side, as if my ads automatically appears after image or words like click here: .

      Thanks again.

      avatar
      • April 20th, 2017 at 3:22 pm

        Thanks for this point, I had not thought about this. Here are 3 examples.

        1. To add more space around the ads, see this comment. But that will add the space after all ads, not only ads after an image.
        2. To add horizontal lines before and after the ads, insert this into line 39:

          (So, push the original line 39 down, and insert this new line before it.)

          $insertion = '<hr />' . $insertion . '<hr />';

          To change the color of the horizontal line, add this to your functions:

          (This changes to very light gray. You can change #ddd to your desired color, for example, a darker one such as #c0c0c0 or #a9a9a9)

          add_action( 'amp_post_template_css', 'my_amp_css_styles_hr' );
          function my_amp_css_styles_hr( $amp_template ) {
              ?>
              hr {
                  border: 0;
                  border-top: 1px solid #ddd;
              }
           
              <?php
          }
          

          Again, that will add lines to all ads, not only ads after an image. To add the lines only if the ad is after an image, try instead example 3, below.

        3. To detect if the ad is after an image, you can try the following solution. This will detect images that end with /> However, please note that, in rare cases, this can also think that there is an image even when there is not. For example, if you have HTML meta tags inserted within paragraph 2 (rare case), this will think that it is an image because the meta tag might end with />. You can try this and see if it works for your site.

          To stop showing an ad after an image, push the original line 39 down and insert this before it:

          // If the paragraph ends with an image, do NOT show an ad.
          $img_end = ' /></p>';
          $length = strlen($img_end);
          if ($length != 0) {
              $ends_with_img = (substr($paragraphs[$index], -$length) === $img_end);
              if ( $ends_with_img ) {
                  $insertion = '';
              }
          }
          

          Or, to only add horizontal lines if the ad comes after an image, push the original line 39 down and insert this before it:

          // If the paragraph ends with an image, surround the ad with horizontal lines
          $img_end = ' /></p>';
          $length = strlen($img_end);
          if ($length != 0) {
              $ends_with_img = (substr($paragraphs[$index], -$length) === $img_end);
              if ( $ends_with_img ) {
                  $insertion = '<hr />' . $insertion . '<hr />';
              }
          }
          
        avatar
    • April 20th, 2017 at 1:56 pm

      Hi tanji,

      The Google guidelines you linked to are for regular Mobile pages. I’m using instead the guidelines specifically for AMP pages (https://support.google.com/adsense/answer/7183212).

      (Note: While Mobile pages may seem similar to AMP, they are very different. Mobile pages are still regular pages as far as Google is concerned (as in, they are coded in HTML). On the other hand, AMP pages are coded with different HTML elements (AMP HTML). Designing for regular Mobile pages is almost outdated, in favor of AMP pages. The exception to this are pages that don’t convert to AMP very well, for example pages with complex forms.)

      For AMP pages, I would stick with the recommended guidelines for AMP pages. I hope this helps. Let me know if this is unclear.

      avatar
  7. June 18th, 2017 at 3:15 am

    I am afraid that ads are displaying on my wordpress AMP posts, but not on the pages. Is there really such an issue or could this be an error on my side.

    avatar
  8. November 18th, 2017 at 2:28 am

    You freaking rock! Thank you so much for taking the time to put this all together. I am a non-coder and could follow your flow and instructions. I have implemented Example 4 and confirm it works beautifully. I appreciate you being awesome!!

    avatar

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]