WordPress, AMP and Ads

Delivering your content not only as HTML, but also using the AMP-HTML subset not only reduces the loading times for your readers, but also improves the score of your site in the Google results. On top of that your site will be proxied by the Google AMP Cache, lowering your server load.

If you are using WordPress, adding AMP support is as easy as installing the AMP-Plugin which is developed by Automattic, the company behind WordPress.

Doing so will likely get you more visitors, but unfortunately there is a drawback: the plugin does not support advertisements out of the box.

So if you – like me – rely on advertisements to cover the server costs, you have to apply some tweaks to get ads on AMP pages as well. This is what this post will be about.

Extending the AMP Plugin

Basically you have to modify your current theme. If you are using an off-the shelf theme, you should create a child-theme – otherwise just extend the functions.php of your custom theme.

AMP uses the amp-ad tag for displaying ads which requires a additional script to work. Currently it also works without adding a script, but it already generates a warning. Lets be safe here and add the required script to the list:


add_action( 'amp_post_template_data', 'xyz_amp_post_template_add_ad_script' );
function xyz_amp_post_template_add_ad_script( $data ) {
	$data['amp_component_scripts']['amp-ad'] = 'https://cdn.ampproject.org/v0/amp-ad-0.1.js';
	return $data;
}

Next we create a filter that injects the actual amp-ad tags into out content:


add_action( 'pre_amp_render_post', 'xyz_amp_add_custom_actions' );
function xyz_amp_add_custom_actions() {
    add_filter( 'the_content', 'xyz_amp_add_ad' );
}

function xyz_amp_add_ad( $content ) {
    // hack for skipping featured-image
    if ( false !== strpos( $content, 'wp-post-image')) {
        // as it unfortunately uses get_post too
        // fixed in AMP 0.4.1
        return $content;
    }

    return
    '<amp-ad width=300 height=250
         type="adsense"
         data-ad-client="$YOUR_ID"
         data-ad-slot="$YOUR_TOP_SLOT">
     </amp-ad>'
    .$content.
    '<amp-ad width=300 height=250
         type="adsense"
         data-ad-client="$YOUR_ID"
         data-ad-slot="$YOUR_BOTTOM_SLOT">
     </amp-ad>';
}

The snippet above assumes you are using google adsense. If you want to integrate a different Ad Network, look here for the specific syntax.