Add Google Adsense AUTO ADS To AMP for WordPress

This shows you how to put Google Adsense AUTO ADS on your WordPress AMP posts. This code works with the official AMP for WordPress plugin. You can easily ad AUTO ADS to your AMP posts with one block of code.

If instead you want to insert regular Adsense ads on AMP pages, see this instead.

For AUTO ADS, the only thing you need to modify in the code below is line 6. On line 6, replace ca-pub-1234567891234567 with your own Google Adsense publisher ID. You can get your publisher ID from any of your ad codes. Your publisher ID is the “data-ad-client” in your ad codes, and it looks like this: ca-pub-1234567891234567.

Then, paste the code into your functions. That is all you have to do to enable Adsense AUTO ADS in your WordPress AMP pages.

/**
* Add Adsense Auto Ads code snippet to AMP HTML body
*/
function isa_amp_add_auto_ads_code( $content ) {

	$publisher_id = 'ca-pub-1234567891234567';

	$ad_code = '<amp-auto-ads type="adsense" data-ad-client="' . $publisher_id . '"></amp-auto-ads>';
	return $ad_code . $content;
}
add_action( 'pre_amp_render_post', 'isa_amp_add_auto_ads_insert' );
function isa_amp_add_auto_ads_insert() {
	add_filter( 'the_content', 'isa_amp_add_auto_ads_code' );
}

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

Explanation of the code

The first part of the code inserts the Adsense Auto Ads code snippet to the AMP HTML body of all your AMP posts and pages. The second part adds the AMP script for AUTO ADS to the head of your AMP pages. This script is different from the regular AMP script for regular Adsense ads.

See more: , ,

We've 5 Responses

  1. October 5th, 2018 at 7:27 pm

    Hello Isabel,

    I don’t understand your code. It seems there is no call to the function isa_amp_auto_ads_script.
    I tried without this function and it seems to be working. The code added for the library is

    <script type='text/javascript' src='https://cdn.ampproject.org/v0/amp-auto-ads-latest.js' async custom-element="amp-auto-ads"></script>

    .
    I am using AMP plugin version 0.7.2.

    Jack
  2. August 17th, 2019 at 4:10 am

    Hey,
    Thanks so much for sharing the code in a simpler way. It only takes 2 bits of lines. I used the Advanced Settings page to manually output the JS code and AMPHTML code in Head and Body.

    Thanks,
    Shyam

    ScorpionGod

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]