Skip to content

Instantly share code, notes, and snippets.

@johnregan3
Last active December 31, 2019 03:01
Show Gist options
  • Save johnregan3/3b66061e992568dc4635f5d473522c6c to your computer and use it in GitHub Desktop.
Save johnregan3/3b66061e992568dc4635f5d473522c6c to your computer and use it in GitHub Desktop.
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();
}
@TedAvery
Copy link

TedAvery commented Mar 2, 2017

Does this require you to create your own AMP template, or is there a hook for the default AMP template if you're satisfied with it already?

@megane9988
Copy link

Thanks it is looking good to me! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment