taxonomy – Duplicate menu items when auto generating menu from product categories

Question

I have been searching for solutions for a problem that many have in WordPress. I wanted to create a menu that automatically adds children and grand children of product categories that are already in the menu. I never found a way that suits my case. So, I managed to get to some point with a custom code (which I am beginner to). Bellow is my code that I have placed in the functions.php file of the child theme.

//add_action('wp_update_nav_menu_item', 'add_children_as_well', 10, 3);
function add_children_as_well($menu_id, $menu_item_db_id, $args){
    $is_taxonomy = $args['menu-item-type'] == 'taxonomy';
    if($is_taxonomy){
        $termchildren = get_term_children( $args['menu-item-object-id'], $args['menu-item-object'] );
        if(!empty( $termchildren )){
            foreach($termchildren as $child){
                $menu_item_data = array(
                    'menu-item-object-id'     => $child,
                    'menu-item-object'        => 'product_cat',
                    'menu-item-parent-id'     => $menu_item_db_id,
                    'menu-item-type'          => 'taxonomy',
                    'menu-item-status'        => 'publish'
                );
                $new_id = wp_update_nav_menu_item( $menu_id, 0, $menu_item_data);
            }
        }
    } 
}

The Procedure

So, when I want the sub-items to be generated I create a new menu, I add the parent product categories and before I click save, I open a new tab, I uncomment the first line of the code above, I save the functions.php file and then I go back to the menu editor and save the menu.

I know this is funny but it works!

Although, there is a problem. When it generates the children, it adds the grandchildren to the parent too, instead of only the children. For example, if there is a product category with the bellow structure:

it generates the menu bellow:

  • Category A
    • Category B1
    • Category B2
    • Category C1
    • Category C2
0
Christos Mitsis 5 months 2022-07-03T12:28:42-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse