Please share the code you’re using to hook into amp_post_template_header and amp_post_template_footer.
It’s like this. I have a class that call from main file of my plugin. Inside class contructor function I called through add_action.
protected function __construct() {
add_action('wp_print_footer_scripts', array($this,'registerSW'),1000);
add_action( 'template_redirect', array( $this, 'renderSW' ), 2 );
add_filter( 'query_vars', array( $this, 'registerQueryVar' ) );
add_action( 'init', array( $this, 'registerRewriteRule' ) );
$this->registerAMPServiceworker();
}
public function registerAMPServiceworker(){
// AMP support
add_action( 'amp_post_template_head', array( $this, 'renderAMPSWScript' ) );
add_action( 'amp_post_template_footer', array( $this, 'renderAMPSWElement' ) );
}
public function renderAMPSWScript(){
echo '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>';
}
public function renderAMPSWElement(){
echo '<amp-install-serviceworker src="'.$this->getSWUrl().'" layout="nodisplay"></amp-install-serviceworker>';
}
It would be helpful if you could provide snippet which can be run as-is. What you’ve shared is hard to debug. This works for me:
<?php
class Try_Service_Worker {
public function __construct() {
$this->registerAMPServiceworker();
}
public function registerAMPServiceworker(){
// AMP support
add_action( 'amp_post_template_head', array( $this, 'renderAMPSWScript' ) );
add_action( 'amp_post_template_footer', array( $this, 'renderAMPSWElement' ) );
}
public function renderAMPSWScript(){
echo '<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>';
}
public function getSWUrl() {
return home_url( '/sw.js' );
}
public function renderAMPSWElement(){
echo '<amp-install-serviceworker src="'.$this->getSWUrl().'" layout="nodisplay"></amp-install-serviceworker>';
}
}
$try_service_worker = new Try_Service_Worker();