Last active
August 28, 2018 04:03
-
-
Save ngearing/2b430618c3400776a39522d37d2fd845 to your computer and use it in GitHub Desktop.
WordPress add sub-menu toggle buttons to any menu.
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 | |
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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment