Last active
August 12, 2019 10:23
-
-
Save debabratakarfa/bbeb4d5c681290078def38e07b9af2b0 to your computer and use it in GitHub Desktop.
Add Navigation Menu to an AMP WordPress Theme
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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