wp-bootstrap/wp-bootstrap-navwalker

Duplicate / Repeat parent menu item as first item in child menu

CullenJWebb opened this issue · 4 comments

I'm having trouble creating a function that takes a parent menu item and adds an exact copy as the first item of its own drop-down menu.

I could do this manually with each WordPress menu that I create but I will be using this navwalker on many sites going forward and this is something I'd prefer to be automatic.

I found a similar request in #519 but the solution there creates an unrelated item to insert into the dropdown.

Thank you in advance for your time and input!

I'm having trouble creating a function that takes a parent menu item and adds an exact copy as the first item of its own drop-down menu.

As a clickable menu item or just like a header?

an exact copy

means a dropdown if it is a dropdown? But then you'd be creating a menu of infinite depth.

As a clickable menu item or just like a header?

Clickable menu item.

an exact copy

means a dropdown if it is a dropdown? But then you'd be creating a menu of infinite depth.

Exact as far as the text, data-bs-toggle, classes, etc., not the dropdown within the parent.

@CullenJWebb please note that this question is totally unrelated to the WP Bootstrap Navwalker. However, try this or use it as start for further adjustments. The code loops through all menu items of a menu associated with the theme location primary. If and only if a menu item has the class menu-item-has-children it is considered to be a parent menu item. It is then cloned and added to the array of menu items as it's own child.

add_action( 'wp_nav_menu_objects', 'slug_clone_parent_menu_item', 10, 2 );
function slug_clone_parent_menu_item( $sorted_menu_items, $args ) {
	// Only apply modifications for the theme location 'primary'.
	if ( 'primary' !== $args->theme_location ) {
		return $sorted_menu_items;
	}

	$new_items  = array();
	$menu_order = 1;
	foreach ( $sorted_menu_items as $item ) {
		$item->menu_order = $menu_order;
		$new_items[]      = $item;

		if ( in_array( 'menu-item-has-children', $item->classes, true ) ) {
			$parent_clone = clone $item;
			foreach ( $parent_clone->classes as $key => $value ) {
				if ( 'menu-item-has-children' === $value ) {
					unset( $parent_clone->classes[ $key ] );
				}
			}

			$parent_clone->menu_item_parent = (string) $item->ID;
			$parent_clone->menu_order       = ++$menu_order;

			$new_items[] = $parent_clone;
		}
		++$menu_order;
	}
	return $new_items;
}

Please consider closing the issue if the proposed solution solves your problem.

Thank you @IanDelMar ! That has put me on the right track.