Skip to content

Instantly share code, notes, and snippets.

@vanduc1102
Last active August 28, 2020 17:26
Show Gist options
  • Save vanduc1102/817f0671bfa7ca58dd9a2c052208f59a to your computer and use it in GitHub Desktop.
Save vanduc1102/817f0671bfa7ca58dd9a2c052208f59a to your computer and use it in GitHub Desktop.
Add missing AMP scripts to Wordpress HTML HEAD

ISSUE

The tag 'amp-accordion extension .js script' appears more than once in the document. This will soon be an error.

The tag 'amp-carousel extension .js script' appears more than once in the document. This will soon be an error.

Reason

AMPforWP is using AMP as dependencies, AMP will add amp-scripts base on the Post content somehow at some senarios, it cant add the amp-scripts, so missing script error will appear on the AMP validator.

Solution 1

add_action(
	'amp_post_template_head',
	function() {
		?>
	<script async custom-element="amp-accordion" src="https://cdn.ampproject.org/v0/amp-accordion-0.1.js"></script>
	<script async custom-element="amp-carousel" src="https://cdn.ampproject.org/v0/amp-carousel-0.1.js"></script>
		<?php
	},
	1000
);

This one lead to duplication of scripts tag,

Solution 2

add_filter( 'amp_post_template_data', 'lid_add_missing_amp_scripts' );
function lid_add_missing_amp_scripts( $data ) {
	if ( empty( $data['amp_component_scripts']['amp-accordion'] ) ) {
		$data['amp_component_scripts']['amp-accordion'] = 'https://cdn.ampproject.org/v0/amp-accordion-0.1.js';
	}
	if ( empty( $data['amp_component_scripts']['amp-carousel'] ) ) {
		$data['amp_component_scripts']['amp-carousel'] = 'https://cdn.ampproject.org/v0/amp-carousel-0.1.js';
	}
	return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment