Create Custom AMP for your WordPress News Site

Nowadays more and more News Sites start using the new AMP technology on their websites to gain more speed and more traffic from Google Search as Google seems to prefer AMP Powered websites and you will be able to get better positions if you are able to serve an AMP Version of your page. On this post you will see how to demonstrate AMP to your WordPress website without using a ready made plugin, we will actually create our own custom AMP Plugin for WordPress.

Whats is AMP ?

AMP (Accelerated Mobile Pages) is actually a very light version of a page that loading much faster from our normal version of website as AMP does not load a tone of CSS Styles and Javascript. That’s the reason also Google prefers an AMP version , because Google love fast websites and will rank them in better compared to slow websites.


On the above screenshot you have probably noticed a lighting icon (⚡) in front of the url. This means the this search result can serve an AMP version of the website.

1st Step: Create a blank WordPress Plugin

If you are not familiar with creating plugins on WordPress don’t worry about it it’s very easy to create a plugin where we later add some hooks to create the AMP version of our Website.

Use an FTP Manager like FileZilla or WinSCP and navigate to wp-content/plugins/  directory and create a new folder with name custom-amp and enter to this directory.

Next step is too create an index.php file inside it and leave it empty.

After this step create one more php file and name it custom-amp.php. After creating the file open your favourite text editor and paste the below code , save and re-upload the edited file to your website.

<?php
/*
Plugin Name: Custom AMP
Plugin URI:  https://www.voodal.com
Description: AMP Plugin
Version:     1.0
Author:      Voodal
Author URI:  https://www.voodal.com
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
?>

What we did? We just created a plugin with name “Custom AMP” . Let’s activate our new plugin by going to Plugins -> Installed Plugins find the plugin “Custom AMP” and enable it. This plugin now doing nothing actually because it’s empty so, let’s add some code inside it .

Create AMP Endpoint on WordPress

Before ?> and after */ paste the following contents on custom-amp.php

function custom_amp_endpoint(){
    add_rewrite_endpoint( 'amp', EP_PERMALINK);
}

add_action( 'init', 'custom_amp_endpoint' );

The above hook will create a custom endpoint amp .

Note:After Adding this hook be sure that you go to Settings-> Permalinks and press Save to take effect the new endpoint we just added

Create Template for Single Post

Inside custom-amp folder create a new folder with name templates and enter into this folder and create a new php file single.php and open it with your text editor and paste the following code and save the file.

Don’t forget to replace author name, publisher name and logo to your own.

<?php
global $post;
?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $featured_url =  wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "full" ); ?>

<!doctype html>
<html amp lang="en">
  <head>
    <meta charset="utf-8">
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <title><?php the_title(); ?></title>
    <link rel="canonical" href="<?php echo get_the_permalink();?>">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <script type="application/ld+json">
      {
        "@context": "http://schema.org",
        "@type": "NewsArticle",
        "headline": "<?php the_title(); ?>",
        "datePublished": "<?php echo get_the_date('c'); ?>",
        "dateModified": "<?php echo get_the_modified_date('c'); ?>",
        "mainEntityOfPage": "<?php echo get_the_permalink();?>",
         "author": {
          "@type": "Organization",
          "name": "Voodal"
        },
        "publisher": {
          "@type": "Organization",
          "name": "Voodal",
          "logo": {
            "@type": "ImageObject",
            "url": "https://voodal.com/wp-content/uploads/voodal-logo.png",
            "width": 200,
            "height": 39
          }
        },
        "image": [
          "<?php echo $featured_url[0]; ?>"
        ]
      }
    </script>
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style>
 


    </noscript>
    
  </head>
  <body>
<div id="content" class="site-content">


<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

  <header class="entry-header">
    <div class="container">
      <div class="columns is-centered">
        <div class="column is-6 has-text-centered">
          <?php the_title( '<h1 class="title is-size-3-mobile is-size-3-tablet is-size-1-desktop">', '</h1>' ); ?>
          <?php if ( has_excerpt( $post->ID ) ) { ?>
            <?php the_excerpt(); ?>
          <?php } ?>
          <?php if ( 'post' === get_post_type() ) : ?>
          <div class="entry-meta is-size-6-mobile">

            <?php if ( is_single() ) : ?>
              <?php echo __( 'In', 'voodal' ) . ' '; the_category( ', ' ); ?>
              <span>•</span>
              <a href="<?php the_permalink(); ?>" title="<?php echo get_the_date(); ?>"><?php echo get_the_date(); ?></a>

            <?php endif; ?>
          </div><!-- .entry-meta -->
          <?php endif; ?>
        </div><!-- column -->
      </div><!-- columns -->
    </div><!-- container -->
  </header><!-- entry-header -->

  <section class="entry-content">
    <div class="container">
      <div class="columns is-centered">
        <div class="column is-6">
          <?php if ( has_post_thumbnail() ) : ?>
            <div class="image featured-image">
              <amp-img alt=""
  src="<?php echo $featured_url[0]; ?>"
  width="<?php echo $featured_url[1]; ?>"
  height="<?php echo $featured_url[2]; ?>"
  layout="responsive">
</amp-img>
            </div>
          <?php endif; ?>
<?php
ob_start();
the_content();
$content_data = ob_get_clean();
$content_data = preg_replace('/style=[^>]*/', '', $content_data);
$content_data = preg_replace('/<img(.*?)\/?>/', '<amp-img$1 width="800" height="610" layout="responsive" alt="AMP"></amp-img>',$content_data);

?>
          <?php echo $content_data ; ?>
        </div><!-- column -->
      </div><!-- columns -->
    </div><!-- container -->
  </section><!-- entry-content -->

  <?php if ( get_edit_post_link() ) : ?>
    <footer class="entry-footer">
      <div class="container">
        <div class="columns is-centered">
          <div class="column is-6">

            <?php if ( get_the_tags() ) : ?>
              <p class="tags"><?php the_tags( ' #', ' #', ' ' ); ?></p>
            <?php endif; ?>


          </div><!-- column -->
        </div><!-- columns -->
      </div><!-- container -->
    </footer><!-- entry-footer -->
  <?php endif; ?>

</article><!-- #post-<?php the_ID(); ?> -->

  

  </div>



  </body>
</html>
<?php endwhile; endif; ?>

Connect single.php when amp version is requested.

Open custom-amp.php again and paste the below code

function amp_read_single_template( $single_template) {
    global $post, $wp_query;
    if(array_key_exists( 'amp', $wp_query->query_vars ) )
    	{
         $single_template = dirname( __FILE__ ) . '/templates/single.php';
    	}


    return $single_template;
}
add_filter( 'single_template', 'amp_read_single_template' );

The above hook will check if our url ending with /amp and instead of the normal single post template will serve the AMP version of the post.

Add amphtml before </head>

Add also the following code to your custom-amp.php file .

The below hook will actually inform Google that is also an AMP page is also available for this post

function custom_amp_add_amptml_meta() {
global $post_type;
	if (is_single()) {
		$current_url = get_permalink();
		$amp_current_url = $current_url . 'amp/';
		?>
	
<link rel="amphtml" href="<?php echo $amp_current_url; ?>">

		<?php
	}
}

add_action('wp_head', 'custom_amp_add_amptml_meta', 1);

Note: Be sure that you have re-saved permalinks for /amp endpoint to take effect/

Now open your browser and navigate to a single blog post and append /amp on the end of the url and navigate to this url. Your AMP Page is ready!

On the next post we will see how to add a menu on our AMP page , a footer and how to integrate Google Analytics with AMP

Leave a Reply

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

In WordPress

[Hook] Add Product Schema Markup on WooCommerce Products

With this snippet you will be able to add manually without using a plugin product schema on your WooCommerce Products automatically . Just copy and paste the following Code to your child theme. Don’t forget to change the currency symbol and the Organisation name

Read More

In Hosting, WordPress

What WordPress Hosting to Choose – (2019 Guide) – Comparison

Are you currently searching for a reliable hosting provider for your WordPress site or you are starting a new website and don’t know what hosting plan and provider to choose? If yes, continue reading, as we will analyze some of the most popular hosting providers. And you will be able to make the correct choice […]

Read More

In Web Development, WordPress

Install WordPress on SiteGround using Softaculous

This tutorial explains how to use Softaculous to install a WordPress application on your site. It will take only few minutes and literally no advanced skills to have a fully functional WordPress instance in your hosting account. If you don’t have a Siteground account you can click here to create a new one First, login […]

Read More