I'm using a wp_get_nav_menu_items filter to automaticaly add sub categories to a categories menu. here is the code :

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

if (is_admin()) {
        return $items;
foreach ($items as $index => $i) {
        if ("category" !== $i->object) {
        $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);

Working as expected, this is the result :


but since bootstrap based menus don't allow for click on the parent menu element, and i want to keep it that way for touch devices, i would like to have the base category to show as the first sub element like so :


Have been searching / trying for 2 hours how to do that, figured i might as well ask people who may already know.

  • In the end I added the category directly in the WP appearance -> menu, don't know why it did not occure to me in the first place, but i'm still interested to understand what i did wrong in all my trials. – Xavier C. Mar 21 at 17:49

Your Answer

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

Browse other questions tagged or ask your own question.