Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Removes the ul wrapper on any sub-menus beyond the 2nd level.
<?php
/**
* Limit the number of sub-menu levels outputted.
*
* Removes the ul wrapper on any sub-menus beyond the 2nd level.
*
* @author Joshua David Nelson, josh@joshuadnelson.com
*/
// Add menu walker to primary menu
add_filter( 'wp_nav_menu_args', 'jdn_primary_menu_args' );
function jdn_primary_menu_args( $args ) {
if( isset( $args['theme_location'] ) && 'primary' == $args['theme_location'] ) { // change based on the location
$walker = new JDN_Primary_Nav_Walker;
$args['walker'] = $walker;
}
return $args;
}
// Custom Walker
class JDN_Primary_Nav_Walker extends Walker_Nav_Menu {
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
// Remove 'menu-item-has-children' class from elements beyond the second depth level
if( $depth > 1 && isset( $item->classes ) && is_array( $item->classes ) && ( $key = array_search( 'menu-item-has-children', $item->classes ) ) !== false ) {
unset( $item->classes[ $key ] );
}
parent::start_el( $output, $item, $depth, $args );
}
// Starting of a sub-menu
function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
if( $depth < 2 ) {
$output .= "\n$indent<ul class='sub-menu'>\n"; // The default wrap
} elseif( $depth >= 2 ) {
$output .= "\n$indent\n"; // no sub menu wrap
}
}
// End of a sub-menu
function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
if( $depth < 2 ) {
$output .= "$indent</ul>\n"; // the default wrap end
} elseif( $depth >= 2 ) {
$output .= "\n$indent\n"; // no wrap
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.