更改主菜单

时间:2017-12-30 07:02:12

标签: php wordpress woocommerce

我有主菜单,另一个菜单保存为第二菜单。我想以编程方式更新主菜单的内容,方法是将第二个菜单中的项目添加到子菜单'shop'的主菜单中(当然要删除现有的菜单)。将有几个“第二个菜单”,内容将根据此处不感兴趣的逻辑而改变。

以下代码不起作用,它会创建损坏的菜单项:

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;
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我是通过将标题和网址从另一个菜单复制到主菜单来完成的。通过这种方式,我可以保留几个另外的菜单'并根据特定逻辑更新主菜单所需的部分(=产品)(在这种情况下基于get_site_vorigin())。

add_filter('wp_get_nav_menu_items', 'custom_get_nav_menu_items', 10, 2);

function custom_get_nav_menu_items($items, $menu, $args) {
  if($menu->slug != 'main-menu') { // only for main-menu
    return $items;
  }

  $start_replacing = false;
  $counter = 0;

  $submenu_items = get_sub_menu_items(get_site_vorigin());

  foreach ($items as $item) {
    if ($start_replacing) {
      $inner_counter = 0;
      foreach ($submenu_items as $submenu_item) {
        if ($inner_counter == $counter) {
          $item->title = $submenu_item->title;
          $item->url = $submenu_item->url;
          $item->description = $submenu_item->description;
          $item->target = $submenu_item->target;
        }
        $inner_counter++;
      }
      $counter++;
    }
    if (strtolower($item->title) == 'products') {
      $start_replacing = true;
    }
  }

  return $items;
}

function get_sub_menu_items($submenu_name) {
  $submenu_obj = get_term_by('name', $submenu_name, 'nav_menu');
  $submenu_id = $submenu_obj->term_id;
  return wp_get_nav_menu_items($submenu_obj->term_id);
}