Skip to content

Instantly share code, notes, and snippets.

@pradeep910
Last active April 2, 2019 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pradeep910/59fb3730686de7e30f7ac2828dcaf4ce to your computer and use it in GitHub Desktop.
Save pradeep910/59fb3730686de7e30f7ac2828dcaf4ce to your computer and use it in GitHub Desktop.
Include amp-runtime script for Non-AMP pages.
<?php
/**
* Plugin Name: AMP Framework enabler for Non AMP.
* Description: Enables AMP as Framework enabler for Non AMP.
* Plugin URI: https://rtcamp.com
* Version: 0.2
* Author: rtCamp, pradeep910
* Author URI: https://rtcamp.com
*
* @package rtCamp
*/
/**
* AMP Init function to load scripts and styles.
*/
function rt_amp_init() {
// Skip if current page is AMP page already.
if ( is_admin() || ( function_exists( 'is_amp_endpoint' ) && ! is_amp_endpoint() ) ) {
return;
}
// Include amp-runtime script.
add_action( 'wp_enqueue_scripts', 'rt_load_amp_script' );
// Add amp_boilerplate css code.
add_action( 'wp_head', 'rt_amp_boilerplate_css' );
}
add_action( 'init', 'rt_amp_init' );
/**
* Include amp-runtime script for AMP components.
*/
function rt_load_amp_script() {
wp_enqueue_script( 'amp-runtime', 'https://cdn.ampproject.org/v0.js', [], null );
}
/**
* Filter Script Loader Tag to filter scripts with async tags.
*
* @param string $tag Script tag markup.
* @param string $handle Script handle name.
*
* @return mixed
*/
function rt_add_script_async_attribute( $tag, $handle ) {
// Use script handle check to add async parameter to script.
$async_script_handle = 'amp-runtime';
if ( $async_script_handle === $handle ) {
return str_replace( ' src', ' async="async" src', $tag );
}
return $tag;
}
add_filter( 'script_loader_tag', 'rt_add_script_async_attribute', 10, 2 );
/**
* Add AMP Boilerplate CSS
*/
function rt_amp_boilerplate_css() {
echo '<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>'; // WPCS: xss ok.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment