Skip to content

Instantly share code, notes, and snippets.

@debabratakarfa
Last active August 12, 2019 10:23
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 debabratakarfa/bbeb4d5c681290078def38e07b9af2b0 to your computer and use it in GitHub Desktop.
Save debabratakarfa/bbeb4d5c681290078def38e07b9af2b0 to your computer and use it in GitHub Desktop.
Add Navigation Menu to an AMP WordPress Theme
<?php
/**
* Register the amp-sidebar component script with WP AMP.
*/
function add_amp_sidebar_component_script( $data ) {
$data['amp_component_scripts']['amp-sidebar'] = 'https://cdn.ampproject.org/v0/amp-sidebar-0.1.js';
return $data;
}
add_filter( 'amp_post_template_data', 'add_amp_sidebar_component_script' );
/**
* Render a menu with AMP clean markup.
*
* @param string $location The desired Menu Location.
*
* @return string Return AMP clean html.
*/
function amp_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 menu name empty.
*/
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 ); ?>"><?php echo esc_html( $menu_item->title ); ?></a></li>
<?php }
endforeach;
return ob_get_clean();
}
<?php
/*
* Add the following button to your single.php template file
* wherever you need it.
*
* The "site-menu" label can be called whatever you want,
* but it must match the id of the amp-sidebar element.
*/
?>
<button class="menu-toggle" on='tap:site-menu.toggle' aria-label="Toggle Navigation">
<?php esc_html_e( 'Navigation', 'amp-nav-menu' ); ?>
</button>
<?php
/*
* Add the following HTML markup immediately after the opening
* <body> tag in your AMP template file (single.php).
*
* The AMP Spec requires that this be a direct child of <body>,
* and only one of these is allowed on a page.
*/
?>
<amp-sidebar id="site-menu" layout="nodisplay">
<ul>
<?php
// Replace 'primary' with whatever menu location you need.
echo wp_kses_post( amp_clean_nav_menu_items( 'primary' ) );
?>
<li on="tap:site-menu.close"><?php esc_html_e( 'Close', 'amp-nav-menu' ); ?></li>
</ul>
</amp-sidebar>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment