WordPrssのカスタムメニューをAMPのamp-sidebarで利用する

<?php
// カスタムメニューをamp-sitebarに対応
function mgn_add_site_nav() {
	if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
		function mgn_clean_nav_menu_items( $location ) {
			$locations = get_nav_menu_locations();
			if ( empty( $locations[ $location ] ) ) {
				return '';
			}
			$menu       = wp_get_nav_menu_object( $locations[ $location ] );
			$menu_items = wp_get_nav_menu_items( $menu->term_id );
			if ( empty( $menu_items ) || ! is_array( $menu_items ) ) {
				return '';
			}
			ob_start();
			foreach ( $menu_items as $key => $menu_item ) : ?>
				<li><a href="<?php echo esc_url( $menu_item->url ); ?>"
				       data-vars-clickurl="<?php echo esc_url( $menu_item->url ); ?>"><?php echo esc_html( $menu_item->title ); ?></a>
				</li>
			<?php endforeach;

			return ob_get_clean();
		}

		?>
		<script async custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"></script>
		<amp-sidebar id="site-menu" layout="nodisplay" class="amp-sidebar">
			<ul>
				<?php echo wp_kses_post( mgn_clean_nav_menu_items( 'primary' ) ); ?>
			</ul>
		</amp-sidebar>

		<?php // Note that "site-menu" matches the id of the amp-sidebar element.
		?>
		<button on='tap:site-menu.toggle' class='toggle'><?php esc_html_e( 'Open Menu', 'wp-amp-tutorial' ); ?></button>
	<?php } else {
		wp_nav_menu( array(
			'theme_location' => 'primary',
			'container'      => 'div',
			'depth'          => 1,
			'menu_class'     => 'site-nav',
			'menu_id'        => 'site-nav',
		) ); ?>
		<button on='tap:site-menu.toggle' class='toggle'
		        id='navtoggle'><?php esc_html_e( 'Open Menu', 'wp-amp-tutorial' ); ?></button>
	<?php }
}

add_action( 'after_site-header', 'mgn_add_site_nav', 1 );