Skip to content

Instantly share code, notes, and snippets.

@megclaypool
Last active September 22, 2023 22:33
Show Gist options
  • Save megclaypool/88bc0ddabd9a73090ae569a0a87cbbb1 to your computer and use it in GitHub Desktop.
Save megclaypool/88bc0ddabd9a73090ae569a0a87cbbb1 to your computer and use it in GitHub Desktop.
[Add a submenu toggle button to WordPress menu items with children] Here are the PHP code and JS that will let you create a toggle and cause it to actually toggle classes and aria-expanded attributes. Use styles to show and hide the submenu, and to
// Add this to an appropriate php file in your theme
// Change the function name and the "visually-hidden" class name as appropriate
// Note that this is a WireMedia theme, so is using their icons function.
// You can use css to create the chevron instead
require_once 'icons.php';
function j40a_parent_menu_item_buttons($output, $item, $depth, $args) {
if (in_array('menu-item-has-children', $item->classes, true)) {
$output = $output . '<button type="button" class="menu-item__toggle"
aria-expanded="false" aria-controls="sub-menu-' . $item->ID . '">
<span class="visually-hidden">Toggle Submenu</span>' . get_icon('angle-down') .
'</button>';
}
return $output;
}
add_filter('walker_nav_menu_start_el', 'j40a_parent_menu_item_buttons', 10, 4);
"use strict";
var menuDropdownToggles = document.querySelectorAll(
".menu-item-has-children > button.menu-item__toggle"
);
function toggleMenuDropdown() {
if (this.getAttribute("aria-expanded") == "true") {
this.setAttribute("aria-expanded", "false");
this.parentNode.classList.remove("menu-item--open");
} else {
this.setAttribute("aria-expanded", "true");
this.parentNode.classList.add("menu-item--open");
}
}
// menuDropdownToggles.forEach(function (toggle) {
menuDropdownToggles.forEach(function (toggle) {
toggle.addEventListener("click", toggleMenuDropdown);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment