Skip to content

Instantly share code, notes, and snippets.

@ngearing
Last active August 28, 2018 04:03
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 ngearing/2b430618c3400776a39522d37d2fd845 to your computer and use it in GitHub Desktop.
Save ngearing/2b430618c3400776a39522d37d2fd845 to your computer and use it in GitHub Desktop.
WordPress add sub-menu toggle buttons to any menu.
<?php
function render_sub_menu_toggle( $item_output, $item, $depth, $args ) {
$children = false;
// If menu is using a walker.
// Walker class has children method.
if ( $args->walker->has_children ) {
$children = true;
} else {
// Else have to test for children.
$items = wp_get_nav_menu_items( $args->menu->term_id );
$parents = array_map(
function( $item ) {
return is_object( $item ) ? $item->post_parent : $item['post_parent'];
}, $items
);
if ( in_array( (int) $item->object_id, $parents ) ) {
$children = true;
}
}
if ( $children ) {
// Load sub menu script.
// First wp_register_script in functions.php.
wp_enqueue_script( 'sub-menu-js' );
$title = $item->post_title ?: $item->title;
$item_output .= "<button class='sub-menu-toggle' value='Show sub menu for $title'></button>";
}
return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'render_sub_menu_toggle', 10, 4 );
;(function() {
'use strict'
const toggles = document.querySelectorAll('.sub-menu-toggle')
if ( ! toggles ) {
return;
}
for (let index = 0; index < toggles.length; index++) {
let menuToggle = toggles[index]
menuToggle.addEventListener('click', toggleSubMenu)
}
function toggleSubMenu(e) {
let menu = this.parentNode
menu.classList.toggle('sub-menu-open')
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment