Reputation: 579
I have created a menu which have several items (WooCommerce categories), each of them having few child items (WooCommerce products).
I'm struggling to retrieve the sub items of a parent menu item.
Im getting the parent item using this code:
$the_menu = wp_get_nav_menu_object('Some Menu');
$the_menu_items = wp_get_nav_menu_items($the_menu);
foreach ($the_menu_items as $index => $menu_item) {
if ($menu_item->object_id == $category->term_id ) {
$category_submenu = $menu_item;
}
}
How can I retrieve the child items of current parent item?
Thank you in advance!
Upvotes: 0
Views: 4262
Reputation: 13786
Here is my solution. Looping through menu "MENU NAME" and then showing only items that have the parent PARENT_ID.
<ul>
<? foreach (wp_get_nav_menu_items('MENU_NAME') as $r) {
if ($r->menu_item_parent == PARENT_ID) { echo '<li><a href="'.$r->url.'">'.$r->title.'</a></li>'; }
} ?>
</ul>
Upvotes: 1
Reputation: 4227
You need a recursion for all childs.
Here the example
if ( ! function_exists( 'recursive_mitems_to_array' ) ) {
/**
* @param $items
* @param int $parent
*
* @return array
*/
function recursive_mitems_to_array( $items, $parent = 0 )
{
$bundle = [];
foreach ( $items as $item ) {
if ( $item->menu_item_parent == $parent ) {
$child = recursive_mitems_to_array( $items, $item->ID );
$bundle[ $item->ID ] = [
'item' => $item,
'childs' => $child
];
}
}
return $bundle;
}
}
Usage:
$items = wp_get_nav_menu_items( "Default Theme Menu" ); // Your menu title
$build_tree = recursive_mitems_to_array( $items );
var_dump(build_tree);
Note: correct for your needs.
maybe you need to output html with values.
This example should return nested array (not fully tested)
Upvotes: 5
Reputation: 579
As a workaround I have this temporary solution:
$the_menu = wp_get_nav_menu_object('Some Menu');
$the_menu_items = wp_get_nav_menu_items($the_menu);
$category_products = [];
foreach ($the_menu_items as $index => $menu_category) {
if ($menu_category->object_id == $category->term_id ) {
$category_submenu = $menu_category;
}
}
foreach ($the_menu_items as $index => $menu_product) {
if ($menu_product->type_label == 'Product'
&& $menu_product->menu_item_parent == $category_submenu->ID
) {
$category_products[] = $menu_product;
}
}
I'm parsing all menu items (both parent items and sub items), getting the necessary item based on current category ID and then retrieving the sub items (products) of each category by parsing all the items one more time and checking if current item (product) parent ID matches with the parent category item ID and I just put it into an array.
Upvotes: 0