Sunday, July 3, 2022
HomeWordPress Developmenttaxonomy - Duplicate menu objects when auto producing menu from product classes

taxonomy – Duplicate menu objects when auto producing menu from product classes


I’ve been trying to find options for an issue that many have in WordPress. I needed to create a menu that mechanically provides youngsters and grand youngsters of product classes which are already within the menu. I by no means discovered a manner that fits my case. So, I managed to get to some level with a customized code (which I’m newbie to). Bellow is my code that I’ve positioned within the capabilities.php file of the kid theme.

//add_action('wp_update_nav_menu_item', 'add_children_as_well', 10, 3);
perform 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 $youngster){
                $menu_item_data = array(
                    'menu-item-object-id'     => $youngster,
                    '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 Process

So, once I need the sub-items to be generated I create a brand new menu, I add the mother or father product classes and earlier than I click on save, I open a brand new tab, I uncomment the primary line of the code above, I save the capabilities.php file after which I am going again to the menu editor and save the menu.

I do know that is humorous nevertheless it works!

Though, there’s a drawback. When it generates the youngsters, it provides the grandchildren to the mother or father too, as a substitute of solely the youngsters. For instance, if there’s a product class with the bellow construction:

it generates the menu bellow:

  • Class A
    • Class B1
    • Class B2
    • Class C1
    • Class C2
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments