Integrating AMP into WordPress: A Comprehensive Guide

Authored by

AMP is an emerging technology that’s gaining the attention of online marketers in all fields.  It formats content in a way that loads blazingly fast for mobile visitors, whose page load time expectations can be as little as three seconds.

Abraham Lincoln has no patience for bad UX.

I recently worked with a client who wanted to improve their page load times by integrating the AMP project into their existing WordPress site.  This was a great opportunity for me to expand my toolset, as well as learn something that I can now share with you.

Below you’ll find (perhaps too much) information to get you rolling with AMP, as well as many code samples to help you include AMP in your WordPress projects.

Contents

What is AMP?


AMP stands for “Accelerated Mobile Pages.” It is an Open Source project backed by Google that makes web pages load really, really fast.  These pages are cached and served by Google itself, receive it’s “Mobile-friendly” label in search results, and can even increase Search PageRank for these pages.

Further reading: What is AMP?

After all of the advances that have been made over the last 25 years to give users a rich web experience, AMP takes a huge step backward toward making things as basic as possible.

Kickin’ it old school.

Surprisingly, AMP actually restricts the amount and type of resources that can be loaded on a page. As an example, AMP prohibits these elements, which are often slow-loading:

  • Frame
  • Object
  • Embed

AMP HTML

AMP HTML is quite simple.  It’s nearly identical to regular HTML, with the exception that certain element tags are replaced with an AMP version.  For instance, the <img /> tag becomes <amp-img></amp-img>.

Further reading (highly recommended): The AMP Spec Document

The AMP standard offers alternatives for the following elements (among others) by adding specialized markup elements:

  • Iframes (<amp-iframe>)
  • Video (<amp-video>)
  • Audio (<amp-audio>)

Required Markup

AMP HTML documents MUST contain the following information:

  • start with the doctype <!doctype html>.
  • contain a top-level <html ⚡> tag (<html amp> is accepted as well).
  • contain <head> and <body> tags (They are optional in HTML).
  • contain a <link rel="canonical" href="$SOME_URL" /> tag inside their head that points to the regular HTML version of the AMP HTML document or to itself if no such HTML version exists.
  • contain a <meta charset="utf-8"> tag as the first child of their head tag.
  • contain a <meta name="viewport" content="width=device-width,minimum-scale=1"> tag inside their head tag. It’s also recommend to include initial-scale=1 as it is required to ensure GPU rasterization is enabled.
  • contain a <script async src="https://cdn.ampproject.org/v0.js"></script> tag inside their head tag.
  • contain the AMP boilerplate code (‘head > style[amp-boilerplate]‘ and ‘noscript > style[amp-boilerplate]‘) in their head tag.

Example document <head>:

AMP CSS

AMP requires no special CSS styles, but, as it strives for performance, it does have the following restrictions:

  • Only inline styles are allowed, and style="" is prohibited. Attributes like layout, width, height, media, placeholder, and fallback (among others) are supported.
  • These inline styles are limited to 50Kb.
  • Loading custom fonts is allowed, with some minor restrictions.
  • Pseudo-selectors, pseudo-classes, and pseudo-elements are only allowed on elements with tag names, with the exception being elements that begin with “amp-“.
  • Classes and IDs that begin with “amp-” are prohibited.
  • -amp-” is restricted for internal use by AMP, and these selectors cannot be targeted by your CSS.
  • overflow (and overflow-y, overflow-x) may not be styled as “auto” or “scroll”.
  • No user-defined element in an AMP document may have a scrollbar.

Prohibited items:

  • @import (for now).
  • !important (but you don’t use that anyway, right?)
  • :not()
  • behavior
  • -moz-binding
  • filter

AMP JS

The basic goal of the AMP JS standard is to prevent blocking the DOM while the page is being loaded.  Thus, no custom JavaScript is allowed, only the JS provided by the AMP custom elements (Extensions).

So, it’s quite restrictive, but that makes your job much easier, eh?

Am I right, or am I right?

AMP Extensions


AMP Extensions are helpful components that extend basic AMP functionality by providing support for commonly-used and important features.

Below are a few noteworthy examples, but there are many other Extensions available.

amp-ad
So your site depends upon ad revenue (who’s doesn’t?).  Thankfully, AMP provides a format for including these in your markup with the AMP Ad extension.

amp-sidebar (or “menu”)
The AMP Sidebar extension is what is commonly used as a menu in WP.  It allows for a button (or other element, like a hamburger icon) to trigger a menu that slides into the page from the side.

This element can only be used once on a page, and it essentially only allows text, images, and accordions, so keep that in mind.

amp-brightcove
Hey, who doesn’t love Brightcove content?  To support the need for this feature, AMP has created the AMP Brightcove Extension.  Note that even if you have a lot of custom parameters to pass into Brightcove, you can still do that.

amp-social-share
AMP Social Share is really quite handy, as it takes care of integrating all kinds of sharing into your template by passing just some basic attributes.

WP Integration


Below are modified samples of the code I’ve used to integrate AMP for my client. I hope it will help save you time and gray hairs when you work with AMP in the future (and I’m sure you will).

The WordPress AMP Plugin

So, let’s talk WordPress.  Automattic has created a great plugin that handles all of the heavy lifting to integrate AMP into your site.

If you’re going to use AMP with a WordPress installation, this plugin is where you start.

Currently, the plugin doesn’t support Pages or Archives, but all other templates’ AMP-ified versions can be accessed by adding /amp/ to the end of their URLs.

This redirects the page to an AMP template that loads all of the essentials, including all of the required scripts mentioned above in the AMP standard markup requirements.

Among other tasks, it loads the proper AMP content into the <head>, converts <img /> tags into <amp-img> tags, and includes custom action/filter hooks so you can specifically edit content on the AMP templates.

Naturally, if you’ve read this far into all of this technical jargon, you’re the type of person who wants to customize your templates.  Below are a few ways to get started.

Registering Custom Post Types

Custom Post Types have to be registered with the AMP plugin for them to be supported by the /amp/ query var.  Here’s how to do that:

Registering Custom Templates

The default template that the AMP plugin uses is sufficient, but you’ll most likely want to modify how it looks.  Luckily, the plugin offers a handy hook that allows you to redirect to custom template files.

I highly recommend making a copy of wp-content/plugins/amp/templates/single.php and adding it to your plugin in a templates/ directory, then start you can start hacking away.

After adding this filter, be sure to flush your rewrite rules by simply visiting Settings > Permalinks in the WP Admin.

Registering Component Scripts for AMP Extensions

Component Scripts are JS files that support AMP Extensions. So, if you’re using amp-audio in your template, be sure to include that script in the WP AMP plugin’s data array.

Social Sharing

Here’s a quick example of what Social Share buttons could look like when you integrate amp-social-share into WP.

Advanced Usage


Integrating some of AMP’s features into WP is a bit more involved.  These code samples outline how I’ve accomplished these tasks.

Adding a Menu

Naturally, every website needs a menu, and adding it through WP takes some work.  Frankly, I’m thankful that AMP has a prepackaged Extension to handle this.

AMP allows one “slide-out” menu per page, which is called “amp-sidebar.”  This must be a direct descendant of the <body> element, and it can only contain text, images, and/or an accordion (amp-accordion).

This takes a little work to set up, but once you’ve got the code, it’s an easy process to repeat.

How all of the fastest developers do it.

Filtering Shortcodes

Shortcodes often use markup that doesn’t meet the AMP standard, and you’ll need to account for that if you want Google to validate it as an AMP page.  This can be a painful, but often necessary, step.

Here, I’m using a hypothetical “[podcast]” custom shortcode to ensure the HTML5 audio is rendered using the correct format.

Wrapping Things Up


Since it was announced in October 2015, AMP has been gaining steam in the marketing world.  Serving web pages quickly to mobile users has been a need for some time, and AMP offers a solid, supported spec for accomplishing just that.  Expect to see more work involving AMP coming your way in the near future.

Take some time and investigate AMP.  Go through the resources below and learn all you can.  Then you’ll be ready for the bleeding-edge of web development.

[…or HackerWoman]
You, when you learn AMP for WP before everyone else at the next WordCamp.

Resources


Add Your Voice!


Was this article helpful?  Do you think AMP will really become a major force in web development?  What are your experiences with AMP?  Share your thoughts below in the comments.

Image credits:

2 thoughts on “Integrating AMP into WordPress: A Comprehensive Guide”

  1. This was super helpful, thanks man. Some updates to your code, though. Not sure if Automattic changed it on you. The one I needed was to load the other component scripts. This one works:

    function ky_amp_component_scripts( $data ) {
    $custom_component_scripts = array(
    ‘amp-sidebar’ => ‘https://cdn.ampproject.org/v0/amp-sidebar-0.1.js’,
    ‘amp-social-share’ => ‘https://cdn.ampproject.org/v0/amp-social-share-0.1.js’,
    ‘amp-carousel’ => ‘https://cdn.ampproject.org/v0/amp-carousel-0.1.js’,
    ‘amp-audio’ => ‘https://cdn.ampproject.org/v0/amp-audio-0.1.js’,
    ‘amp-brightcove’ => ‘https://cdn.ampproject.org/v0/amp-brightcove-0.1.js’,
    );
    $data[‘amp_component_scripts’] = array_merge( $data[‘amp_component_scripts’], $custom_component_scripts );
    return $data;
    }

  2. Everything posted made a bunch of sense. But, what about this?
    suppose you were to create a killer headline? I mean, I don’t want to tell you
    how to run your website, however what if you added a post title to
    maybe get a person’s attention? I mean Integrating AMP into WordPress:
    A Comprehensive Guide – Make XWP is kinda boring.
    You could glance at Yahoo’s front page and see how they create post titles to get viewers to click.
    You might add a related video or a related pic or two to get
    people interested about what you’ve written. Just my opinion, it could make your posts a little bit more interesting.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.