Make WordPress Core

Changeset 54478


Ignore:
Timestamp:
10/11/2022 02:02:55 PM (2 years ago)
Author:
audrasjb
Message:

Menus: Remove .menu-item-has-children on wp_nav_menu last level menu items when $depth arg is used.

This changeset prevents wp_nav_menu last level menu items from having the .menu-item-has-children class when the $depth argument is used. It adds a loop in wp_nav_menu() to calculate the depth of each menu item with children to make sure the class is added only when applicable.

Props slobodanmanic, kucrut, iCaspar, mdgl, petitphp, audrasjb, costdev.
Fixes #28620.

Location:
trunk
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/nav-menu-template.php

    r52684 r54478  
    197197
    198198    $sorted_menu_items        = array();
     199    $menu_items_tree          = array();
    199200    $menu_items_with_children = array();
    200201    foreach ( (array) $menu_items as $menu_item ) {
    201202        $sorted_menu_items[ $menu_item->menu_order ] = $menu_item;
     203        $menu_items_tree[ $menu_item->ID ]           = $menu_item->menu_item_parent;
    202204        if ( $menu_item->menu_item_parent ) {
    203             $menu_items_with_children[ $menu_item->menu_item_parent ] = true;
     205            $menu_items_with_children[ $menu_item->menu_item_parent ] = 1;
     206        }
     207
     208        // Calculate the depth of each menu item with children
     209        foreach ( $menu_items_with_children as $menu_item_key => &$menu_item_depth ) {
     210            $menu_item_parent = $menu_items_tree[ $menu_item_key ];
     211            while ( $menu_item_parent ) {
     212                $menu_item_depth  = $menu_item_depth + 1;
     213                $menu_item_parent = $menu_items_tree[ $menu_item_parent ];
     214            }
    204215        }
    205216    }
     
    208219    if ( $menu_items_with_children ) {
    209220        foreach ( $sorted_menu_items as &$menu_item ) {
    210             if ( isset( $menu_items_with_children[ $menu_item->ID ] ) ) {
     221            if (
     222                isset( $menu_items_with_children[ $menu_item->ID ] ) &&
     223                ( $args->depth <= 0 || $menu_items_with_children[ $menu_item->ID ] < $args->depth )
     224            ) {
    211225                $menu_item->classes[] = 'menu-item-has-children';
    212226            }
     
    214228    }
    215229
    216     unset( $menu_items, $menu_item );
     230    unset( $menu_items_tree, $menu_items_with_children, $menu_items, $menu_item );
    217231
    218232    /**
Note: See TracChangeset for help on using the changeset viewer.