Skip to content

Instantly share code, notes, and snippets.

@msaari
Forked from johnregan3/wp-amp-tutorial-menu.php
Last active February 2, 2017 07:12
Show Gist options
  • Save msaari/71f3395fa05469a5a9bafc133248072a to your computer and use it in GitHub Desktop.
Save msaari/71f3395fa05469a5a9bafc133248072a 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 ) :
$menu_item->menu_item_parent == 0 ? $class = "" : $class = " class='sub' "; ?>
<li<?php echo $class; ?>><a href="<?php echo esc_url( $menu_item->url ); ?>"><?php echo esc_html( $menu_item->title ); ?></a></li>
<?php endforeach;
return ob_get_clean();
}
@msaari
Copy link
Author

msaari commented Feb 2, 2017

My changes add class "sub" to sub menu items (ones that have menu_item_parent != 0).

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