A Comprehensive Guide to Supporting AMP in WordPress

Standard

AMP is a new technology that’s gaining the attention of online marketers in every field.  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.

In this post, we’ll discuss what AMP is, as well as how to wire up your WordPress themes to support AMP templates.  You’ll find a large amount of information and code samples in this post.

Quick Links:


All About AMP

amp-project-logo

AMP stands for “Accelerated Mobile Pages.” It is an open source project backed by Google that makes web pages load really, really fast.  There are also some huge benefits for publishers who take advantage of AMP:

  • AMP pages are cached and served by Google itself.
  • Two versions of the page are now available to search queries: HTML and AMP.
  • They receive Google’s “Mobile-friendly” or “AMP” label in search results, notifying users that the page will load quickly.
  • Google may use AMP as a PageRank consideration in the future (“mobile-friendliness” already is).
google-amp-label

Example of the Google “AMP” label.  Don’t ask why I was googling Pokemon Go.

Further reading: Does Google AMP Affect SEO?

In order for Google to cache your pages and give it the AMP label, it must have valid AMP markup.  AMP HTML is very similar to regular HTML5, with just a few exceptions.

AMP HTML

AMP HTML is quite simple.  In most cases, it’s nearly identical to regular HTML5, 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: The AMP Spec Document

AMP has very specific standards. These standards are in place so that it can render each page as quickly as possible.  Here are some highlights of the requirements for valid AMP documents:

  • The document <head> must contain specific scripts and styles.
  • Only inline styles are allowed (No external stylesheets)
  • The inline styles are limited to 50Kb in size
  • Slow-loading elements — like <frame>, <object>, and  — are prohibited.
  • No custom JavaScript is allowed (but there are several AMP extensions that provide common JS functionality for you)

AMP Extensions (or, “Components”)

AMP Extensions are helpful components that expand what AMP does by default.

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

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.  I’ll discuss this in detail below.

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-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-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 a bunch of sharing into your template by passing just some basic attributes.


The WordPress AMP Plugin

wp-amp-plugin

The good news for you is that the team at Automattic has created a very nice plugin to handle creating valid AMP documents in WordPress.  It’s simply called “AMP,” but for clarity’s sake, I’ll refer to it as “WP AMP” throughout this discussion.

To a user, the plugin simply makes an AMP version of a post is available.  This post is found at the same URL as the post, but with “/amp” tacked on to the end.

So if the URL is yoursite.com/hello-world, the AMP version is found at yoursite.com/hello-world/amp/.

For developers, WP AMP is basically a templating system.  It contains a basic AMP HTML template, and uses hooks and filters to ensure your content is rendered as valid AMP markup.  For example, the provided template includes the required code for the <head>, and it filters the post content to ensure your <img> tags are replaced with <amp-img>.

Further reading: WP AMP plugin documentation

Screen Shot 2016-07-21 at 10.43.13 AM

The default WP AMP post template.


AMP Template Customization for Themes

So, if you’re a theme developer, you’ll want to customize this document’s appearance to match the rest of your layout so that your users will have a seamless visual experience.  The rest of this post discusses how to do just that.

Customizing the WP AMP plugin to work with your theme takes a bit of work, but it will definitely be a big bonus to your users.  As this is a growing technology, there will be increasing demand for the fast page load times and Google recognition that AMP provides.  At this point, it will set your work apart from other WordPress themes.

Basic AMP Support Setup

Note that this tutorial is written for WP AMP version 0.3.2.

1. Set Up Your AMP Directory

To get started, create a directory in your theme called “amp/”.  Inside that directory, create “amp.php.”  We’ll add all of our backend code inside this file.

Now take a step back, and require the amp/amp.php file near the top of your theme’s functions.php:

require( dirname( __FILE__ ) . '/amp/amp.php' );

2.  Register Your Custom Templates

Here’s where the fun begins.  We’ll be adding your own template files so that you can customize them to match your theme.

After this following step, your theme’s file structure should end up looking like this:

your-theme/
   amp/
      templates/
         single.php
         style.php
      amp.php
   functions.php
   index.php
   style.css

 

Start by creating a directory inside of “amp/” called “templates/”.  Not surprisingly, this will hold your template files.

Next, create a file inside templates called “style.php” (note that it’s a PHP file, not CSS).  If you like, you can just copy the default style.php from the WP amp plugin: wp-content/plugins/amp/templates/style.php.

Now, go into the WP AMP plugin and copy the default single.php file (wp-content/plugins/amp/templates/single.php).  Place this in your theme’s “amp/” directory.  It’s important that you copy this one instead of starting from scratch, as there’s important data in its <head>, plus it also contains some of the actions we’ll be hooking into later.

3.  Register Your Custom Templates

Add the function below to include support for both your new “single.php” and “style.php”


Going Further

Support Custom Post Types

If you have Custom Post Types in your theme, you’ll need to tell WP AMP what they are so that those posts will have AMP versions available.

Next, we’ll add our CPT templates.

Custom Post Type Templates

Adding special templates for your custom post types is optional, but the previous step is not.  You’ll want a special CPT template if your CPT posts have a different layout or functionality than a typical post.

In your /templates directory, copy the single.php and rename it after the slug of your CPT.  For instance, you may have a “book.php” now.

Then, we need to tell WP AMP to redirect to this template.  Edit the function that I called jr3_amp_custom_templates() earlier.  It will now look like this:

Component Scripts

Each AMP Extension (once again, also called a “Component”) has a supporting JS resource.

If you’re using any other Extensions in your template files, like amp-ad, amp-social-share, or amp-sidebar, you must register the JS with WP AMP so it gets loaded correctly.


Customizing Your Template

Custom CSS

As AMP does not allow external stylesheets, all CSS must be found in the document’s <head>.  WP AMP gives us a tool for hooking styles into the <head>, which we’ve already set up.  As a reminder, it will use our our templates/style.php file.

The contents of that file are pretty easy to understand.  Open up the default WP AMP style.php and you’ll see that it’s almost all just plain text, except for a few places where colors and a few other settings are pulled in to render the desired CSS styles.

Keep in mind that the total size of CSS on the page cannot exceed 50Kb.

Here is an example of how the PHP interacts with the CSS:

Add A Nav Menu

A Navigation Menu is one feature that is glaringly lacking from the default WP AMP template.  Naturally, its authors are unable to know if you have a nav menu in your theme, and even if they did, they don’t know what location label you’ll give it, so it’s understandable why they left it up to you to customize.

AMP has an Extension called “amp-sidebar.”  This is a block of content that is triggered by a click that slides in from the side of the page.  We’re going to use this for our menu.

Screen Shot 2016-07-21 at 12.58.52 PM

Example of a basic Navigation Menu using amp-sidebar.

First, following the example code below, add two functions to your amp.php:

jr3_amp_sidebar_component_scripts() tells WP AMP to load the amp-sidebar JS into the template’s <head>.  (Check to make sure you didn’t already add this if you added the component scripts earlier)

jr3_clean_nav_menu_items() is a helper function I wrote to make a barebones list of menu items.  It skips adding all of the unneeded wrappers and classes to the nav menu.

Below those functions are two blocks of HTML to add to your single.php (and other template files).  The first is the HTML that holds our primary nav menu.  The next is the actual button that will trigger the opening/closing of the amp-sidebar menu.

By default, featured images are not included in the WP AMP templates.  Here’s how you do that, taken almost directly from the WP AMP docs.

Social Share Buttons

Since social share buttons often require JS to function, AMP has added support for them via its amp-social-share Extension.  The code below can go directly into your template file.  Don’t forget to register the amp-social-share component script with WP AMP.

I’ve found that Facebook requires an App ID, so be sure to add yours into your code.  Naturally, you’ll need to add some PHP support for this to draw the Fb App ID from wherever you have it in your theme’s settings.


Bonus: Handling Shortcodes

As AMP has very specific rules about what markup is allowed, we need to be careful to only allow valid HTML to our templates.

Shortcodes are a way that unintended output can be slipped in to our content and render the page invalid.  One simple (but not preferable) way to prevent this is to remove shortcodes from the content altogether.

Unfortunately, this approach is pretty brutish.  You should really use another solution for this issue, as you may want to allow certain shortcodes, or even filter the content to replace the shortcode with custom formatting.

Here’s an example of how I modified a hypothetical shortcode called “podcast” to accommodate <amp-audio>.  You’ll note that I also include a helper function to grab the shortcode attributes that we need so we can add that data to our <amp-audio> tag.

Final Thoughts

AMP is going to be a big deal, and soon.  In my experience, clients are already asking us at XWP to integrate it into their WP sites.

If you want to stay ahead of the competition in the WP theme world, or offer your clients another valuable service, you definitely need to integrate this into your themes.

I hope that my experience in this speciality will help you on your way.

Happy coding!

Resources

 

Advertisements

Please Change Your Genesis Favicon

Standard

I love the Genesis framework* for WordPress. It is an amazing tool for speeding up the development process, and I even use it on my personal site.

Its wide acceptance across the WordPress world is unfortunately highlighted by the proliferation of Genesis favicons on these sites.

The Genesis Favicon is a black square or circle with a white capital “G” in it. It is a dead giveaway that you’re running your site on Genesis.

If you’re developing custom sites for your clients, you probably don’t want that visible. Your client would probably prefer to have their own branding in their favicon.

The fix for this is pretty simple, thanks to the hooks that Genesis offers.

What is a Favicon?

A favicon is that little square icon that appears in your browser window (or tab). It’s actually not a typical image, but an .ico file type.

The black circle in this browser tab is an example of a Genesis favicon.

The black circle in this browser tab is an example of a Genesis favicon.

To create your own favicon, create a square logo image with your brand of any size larger than 16x16px (you can even use transparent .pngs). Then, go to a site like favicon-generator.org and convert it to an .ico.

Including Your Custom Favicon in a Genesis Child Theme

Typically, this file is named “favicon.ico,” but you can call it whatever you want. The name “favicon.ico” is used in my code sample, so you may have to adjust that as needed.

Add your favicon to your Genesis Child theme’s directory, and add the following code to your child theme’s functions.php.

Note: Browsers are pretty stingy about caching these favicons. This means that you’ll need to open your site in a private/incognito window to see the changes take effect. New visitors to your site won’t need to do this.

*Not an affiliate link

Adding Support for Vertical Featured Images in WordPress Themes

Standard

Here’s a quick and easy way to add support for Vertical Featured images in your WordPress themes.

How it Works

Using a filter hook, we’re going to add a class to the Featured Image markup if the image’s height is greater than its width. Then, using CSS we’ll float it to the right. Pretty simple, huh?

The Script

In your functions.php file add:

The CSS

This code floats the image to the right and adds some margin to separate the image from the post’s content. Be sure to include it in your CSS file.

.vertical-image {
	float:right;
	margin-bottom: 1em;
	margin-left: 2%;
	max-width: 33%;
}

Caveats

Your Post title will need to be clear: none; if this happens:

Screen Shot 2014-01-02 at 2.13.46 PM

You may need to add overflow:hidden to your post’s CSS to prevent this from happening in case the post excerpt is too short:

Screen Shot 2014-01-02 at 1.59.06 PM

The Result

This is what it should look like if the Feature Image has a vertical (portrait) orientation:

Screen Shot 2014-01-02 at 1.53.14 PM

Conclusion

When researching this, I had a hard time finding resources on this topic, so I hope this helps! If you find this post helpful, be sure to pass it on, including a link to this post!

Why you need to get into WordPress Unit Testing

Standard

What is Unit Testing?

A non-technical definition of Unit Testing, is “a way to make sure your code won’t break stuff.” In the WordPress world, it means using a provided library of tests to check if your code will return errors. Basically, it’s a program that you put your code files into, and when you run it, you will be notified if there are problems.

It’s important to know that WordPress Unit Testing is typically done with PHPUnit. You’ll see that name thrown around here and there when researching this topic.

Why Automated Testing?

Holy crap, WHY NOT?

In the past, I wasted a lot of time clicking back and forth between posts and settings pages to ensure that my new plugin or theme wouldn’t throw any errors in a WordPress install. Now, you can just type a few commands and your code will be analyzed quickly and thoroughly. Automated Unit Testing lets you quickly check your code in many, many different contexts and scenarios.

Unit Testing has proven invaluable to me in my attempts to write patches for WordPress Core. One time I ran some code I thought would work, and it broke WordPress in 9 other places. Luckily I was able to test it before I submitted it for review, right?

Unit Testing can also reveal unexpected output. Recently, automated testing revealed to me something I didn’t expect to see: when typical date formats were passed into a function, it executed perfectly, but when just one other date format was sent through, it spit out data I hadn’t accounted for. I’m not sure I would have caught that error on my own. It would have required running my code by hand many times and many ways.

Typically, testing looks like this:

  1. Edit code.
  2. Switch to browser.
  3. Input data (e.g., create a new post/comment, ativate a plugin, change admin settings, etc).
  4. Cross fingers.
  5. Check 80,987,096 places for error messages.
  6. Hope you didn’t miss anything.
  7. Repeat 9,464,643,943 times, just to be sure.
  8. Spend the rest of your day answering support questions about errors caused by your last Plugin.

The automated testing process looks more like this:

  1. Edit code.
  2. Switch to terminal.
  3. Start unit testing ($ phpunit).
  4. Make a glass of ice tea.
  5. Wait for Test Results.
  6. ???
  7. Profit.

How to Test your WordPress App, Theme, Plugin, or Patch

Tom McFarlin wrote a great series on this topic, so I won’t waste time and space trying to explain it all over again (and probably in an inferior way). Check his article out on WPTuts+: The Beginner’s Guide to Unit Testing: What Is Unit Testing? Specifically, check out the section titled “Preparing the Environment.” It will help get you started.

Other Resources

Conclusion

Unit testing is very important. It is way faster and way more thorough than you are. It is powerful and will save you a lot of headaches and embarassment when your code goes live. You need to get into Unit Testing.

Your Turn

So, what has been your experience with Unit Testing? What tips do you have for those getting started? Share your thoughts in the comments!

If you’re ready to get to the meat and potatoes, check out the next post, “Tutorial: Writing a Unit Test for WordPress.”