How to Add Advanced Custom Fields to AMP by Automattic

Including Image Fields that kinda validate!

Want to add your ACF’s to your AMP’s?

If you’re unfamiliar with AMP (Accelerated Mobile Pages) by Google. It’s basically a new way to serve super fast, lightweight compiled versions of a webpage to mobile users. It has its own validation spec. Really really huge honking websites like Polygon, Washington Post and The Verge all use AMP on their news articles.

Which is super awesome, because nothing sucks more than an article taking more than 15 seconds to load over “Transit Wi-fi” on the G Train. These super powered articles are literally instant, taking no more than 1 second to load — even over 4G speeds. Even after all of those pro’s Google takes it one step higher by giving search result priority to AMP powered-articles and pages for mobile searches.

So the first thing you need to do is declare in your functions.php file that you want to use a custom AMP template. Mine looks like this:

php<br>add_filter( 'amp_post_template_file', 'xyz_amp_set_custom_template', 10, 3 );<br>function xyz_amp_set_custom_template( $file, $type, $post ) {<br>if ( 'single' === $type ) {<br>$file = dirname( __FILE__ ) . '/templates/template-amp.php';<br>}<br>return $file;<br>}<br>

Then create a template file in your theme called template-amp.php. Mine is in a directory named templates.

Copy the amp-wp single.php template from the Github master for the latest codebase.

Once you’ve done that, you can add your ACF field in the template as usual! The caveat are ACF image fields which need some AMP-validating like so:


...<br><div class="amp-wp-article-content"><!--?php echo $this->get( 'post_amp_content' ); // amphtml content; no kses ?--><!--?php if( have_rows('editorial_flexible_components') ): ?--><br><!--?php while ( have_rows('editorial_flexible_components') ) : the_row(); ?--><!--?php if( get_row_layout() == 'paragraph' ): ?--><br><!--?php $paragraph_text = get_sub_field('paragraph_text'); ?--><!--?php elseif( get_row_layout() == 'image' ): ?--><br><!--?php // Grab the Image ID from the ACF ?--><br><!--?php $the_image = get_sub_field('the_image'); ?--><br><!--?php $image_url_array = wp_get_attachment_image_src($the_image, 'full', true); ?--><br><!--?php $image_url = $image_url_array[0]; ?--><!--?php // Displaying a ACF Image field that will validate ?--><img class="i-amphtml-fill-content i-amphtml-replaced-content" src="<?= $image_url; ?>" alt="" /><!--?php endif; ?--><br><!--?php endwhile; ?--><br><!--?php endif; ?--></div><br>...

And now, the AMP will deliver your ACF content! Obviously I used Flexible Content fields in my example, but you can use any ACF field in the template-amp.php file, just make sure it validates.

Before (left), and after (right):

Leave a Reply

%d bloggers like this: