AdSense Secondary Domain

Thursday, September 14, 2017

How to add amp-auto-ads code to Wordpress site which uses "AMP for WP"

I've installed "AMP for WP" after Google started punishing it in search results for not having Accelerated Mobile Pages some time ago. And have been playing with it for some times now. The plugin itself is very nice and gives an easy way to set up pages and customize them a bit.

However there doesn't seem to be an easy way to add custom code to the page content itself. There is a way to add code between "<head></head>" tags or to the footer, but there is no such way to do it within "<body></body>" tags. And this is where customized Adsense codes should go if you wish to use some (including responsive ads by the way).

I did get away with using standard plugin way of adding adsense (non-responsive) for a while. However I had to figure alternative way of dealing with this problem today since I've got an invitation to "Accelerated Mobile Pages (AMP) Auto Ads" google labs for my cooking website, enabling of which requires to add some custom code to the AMP page content right after the "<body>" tag.

After few tries to search through forums, FAQs, and websites, this is the solution which I came up with (use it on your own risk, plugin documentation didn't have this hook listed and I had to do some code reviews to find it, so it may not work entirely the way I think, or may stop working in future).

I've hooked into 'ampforwp_body_beginning' (added the following to the functions.php of my theme, replace angled brackets with proper characters and appropriate code in the adsense ca-pub value should you choose to copy/paste the code):

function amp_ads_insert() { echo '<amp-auto-ads data-ad-client="ca-pub-YOUR-CODE-HERE" type="adsense"></amp-auto-ads>'; }
add_action( 'ampforwp_body_beginning', 'amp_ads_insert', 0);

4 comments:

  1. can you provide screen shot how to add the code , and where exactly.

    ReplyDelete
    Replies
    1. Mohamed,
      the code should be added to your wordpress scheme functions.php file, you can usually find it in wp-content/themes/YOURTHEMENAME/

      Somewhere at the bottom should work, as long as you don't break the PHP code. If you plan to copy/paste the code I've provided, don't forget to replace < and > with proper characters after paste or the code will not work.

      Delete


  2. https://wordpress.org/support/topic/adsense-amp-auto-ads-insertation-implementation/

    ReplyDelete
  3. AMP for WP authors are planning to add this feature in ( https://wordpress.org/support/topic/add-amp-gtm-after-opening-body-tag/#post-9539214) so in future this "hack" may not be needed after all. Expecting a plugin update on Oct 7th.

    ReplyDelete