Creating a Menu using amp-sidebar in WordPress
<?php
/**
* Render the Primary Nav Menu
*
* Uses amp-sidebar to handle
* slideout animation.
*
* Be sure to include the amp-sidebar component script.
* Also, rememeber that the amp-sidebar element must be
* a direct child of the <body>.
*
* @action {your custom template action}
*/
function xwp_render_primary_nav() {
?>
<amp-sidebar id="site-menu" layout="nodisplay">
<ul>
<?php echo wp_kses_post( xwp_clean_nav_menu_items( 'primary' ) ); ?>
<li on="tap:site-menu.close"><?php esc_html_e( 'Close', 'wp-amp-tutorial' ); ?></li>
</ul>
</amp-sidebar>
<?php // Note that "site-menu" matches the id of the amp-sidebar element. ?>
<button on='tap:site-menu.toggle'><?php esc_html_e( 'Open Menu', 'wp-amp-tutorial' ); ?></button>
<?php
}
add_action( '{your custom template action}', 'xwp_render_primary_nav' );
/**
* Render a menu with clean markup.
*
* @param string $location The desired Menu Location.
*
* @return string
*/
function xwp_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 ); ?>"><?php echo esc_html( $menu_item->title ); ?></a></li>
<?php endforeach;
return ob_get_clean();
}