1

I have main-menu and another menu saved as second-menu. I want to programmatically update the contents of main-menu by adding the items in second-menu to the main-menu of submenu 'shop' (and of course remove the existing ones). There will be several 'second menus' and the contents will change based on the logic that is not interesting here.

The following code does not work, it will create broken menu items:

add_filter('wp_nav_menu_items', 'custom_shop_menu', 10, 2);

function custom_shop_menu($items, $args) {
  $menu_name = "main-menu";
  $menu_obj = get_term_by('name', $menu_name, 'nav_menu');
  $menu_id = $menu_obj->term_id;
  $menu_items = wp_get_nav_menu_items($menu_id);

  foreach ($menu_items as $menu_item) {
    if (strtolower($menu_item->title) == "shop") {
      $submenu_obj = get_term_by('name', "second-menu", 'nav_menu');
      $submenu_id = $submenu_obj->term_id;
      $submenu_items = wp_get_nav_menu_items($submenu_id);
      foreach ($submenu_items as $submenu_item) {
        $itemData =  array(
          'menu-item-parent-id' => $menu_item->ID,
          'menu-item-type' => $submenu_item->type,
          'menu-item-title' => $submenu_item->title,
          'menu-item-url' => $submenu_item->url,
          'menu-item-description' => $submenu_item->description,
          'menu-item-attr-title' => $submenu_item->attr-title,
          'menu-item-target' => $submenu_item->target,
          'menu-item-classes' => $submenu_item->classes,
          'menu-item-xfn' => $submenu_item->xfn,
          'menu-item-status' => $submenu_item->status
        );
        wp_update_nav_menu_item($menu_id, $submenu_item->db-id, $itemData);
      }
      break;
    }
  }
  return $items;
}

What am I doing wrong?

  • what is broken ? the URL are not good ? – mmm Jan 2 '18 at 20:56

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.