0

I have a menu with a combination of pages and categories. I need to loop through the menu and if it finds a category automatically add all child-categories as a submenu.

Page 1 | Page 2 | Custom Link
                    Category 1
                    Category 2
                        Child Category

In the example above I need to dynamically add the Child Categories to this menu

3

you can add them with the filter wp_get_nav_menu_items

add_filter("wp_get_nav_menu_items", function ($items, $menu, $args) {

    // don't add child categories in administration of menus
    if (is_admin()) {
        return $items;
    }


    foreach ($items as $index => $i) {

        if ("category" !== $i->object) {
            continue;
        }


        $term_children = get_term_children($i->object_id, "category");


        // add child categories

        foreach ($term_children as $index2 => $child_id) {

            $child = get_term($child_id);

            $url = get_term_link($child);


            $e = new \stdClass();

            $e->title = $child->name;
            $e->url = $url;
            $e->menu_order = 500 * ($index + 1) + $index2;
            $e->post_type = "nav_menu_item";
            $e->post_status = "published";
            $e->post_parent = $i->ID;
            $e->menu_item_parent = $i->ID;
            $e->type = "custom";
            $e->object = "custom";
            $e->description = "";
            $e->object_id = 0;
            $e->db_id = 0;
            $e->ID = 0;
            $e->classes = array();

            $items[] = $e;

        }


    }


    return $items;

}, 10, 3);
  • this is only giving me the sub-categories for the last category. – Jason Oct 14 '17 at 14:01
  • I made a mistake with indexes. I edit my answer, can you try again ? – mmm Oct 14 '17 at 14:09
  • Doh, I should have caught that as well. :) That worked, thank you. I started thinking that it might be best practices to add the parent categories as well. In other words, I add a class to the "Custom Link" (menu-item-all-categories) then in the function once it finds that class add all categories and subcategories to that menu item. Can you help tweak your code to handle this? – Jason Oct 14 '17 at 15:19
  • Hi @mmm any chance you can help me out with my latest issue? wordpress.stackexchange.com/questions/282959/… – Jason Oct 15 '17 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.