Skip to content

Instantly share code, notes, and snippets.

@mattradford
Created November 19, 2021 15:37
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 mattradford/1bf6379bb91e52cba4aa0a0473365ccb to your computer and use it in GitHub Desktop.
Save mattradford/1bf6379bb91e52cba4aa0a0473365ccb to your computer and use it in GitHub Desktop.
WordPress nav menu with a title
$menu_locations = get_nav_menu_locations();
// Pass this function a menu location
echo mattrad_nav_menu('footer_one', $menu_locations);
/**
* Output nav menus with a title already!
*
* Includes Alpine.js for show/hide.
*
* @param $menu_location|string
* @param $menu_locations|array
* @return html
**/
function mattrad_nav_menu($menu_location, $menu_locations)
{
if (!array_key_exists($menu_location, $menu_locations)) {
return;
}
$menu_id = $menu_locations[$menu_location];
$menu = wp_get_nav_menu_object($menu_id);
$menu_output = null;
ob_start();
echo '<nav
class="footer__menu footer__menu--'. $menu_location .'"
x-data="{ isOpen: false }"
@keydown.escape="isOpen = false"
aria-labelledby="heading--'. $menu_location .'"
:aria-expanded="isOpen ? \'true\' : \'false\'"
>';
if (isset($menu->name)) {
echo '<p
id="heading--'. $menu_location .'"
class="footer__heading"
@click="isOpen = !isOpen"
role="button"
aria-controls="menu-'. $menu->slug .'"
:aria-pressed="isOpen ? \'true\' : \'false\'"
>' . esc_html($menu->name) . '</h4>';
}
$args = [
'theme_location' => $menu_location,
'depth' => 1,
'container' => '',
'items_wrap' => '<ul id="%1$s" :class="{ \'%2$s hide--mobile\': !isOpen }">%3$s</ul>',
];
wp_nav_menu($args);
echo '</nav>';
ob_end_flush();
return $menu_output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment