WordPress教程

WordPress菜单中的分类自动添加子分类菜单

阿里云

我们在进行 WordPress 主题开发的时候,我们会遇到子分类特别多,而且还要添加到网站导航中的情况。如果导航中只有分类还好弄,可是还有其他自定义菜单项的话,就比较麻烦了。多数时候,要手动去添加顶级分类下的子分类,很费时。下面说下,如何在菜单本身是分类的情况下,自动添加其下的子分类为子菜单。

  1. /* 自动给导航菜单中的分类添加其下的子分类 */
  2. add_filter("wp_get_nav_menu_items", function($items, $menu, $args) {
  3.     if (is_admin()) {
  4.         return $items;
  5.     }
  6.  
  7.     foreach ($items as $index => $i) {
  8.         if ("category" !== $i->object) {
  9.             continue;
  10.         }
  11.         $term_children = get_term_children($i->object_id, "category");
  12.         foreach ($term_children as $index2 => $child_id) {
  13.             $child               = get_term($child_id);
  14.             $url                 = get_term_link($child);
  15.             $e                   = new stdClass();
  16.             $e->title            = $child->name;
  17.             $e->url              = $url;
  18.             $e->menu_order       = 500 * ($index + 1) + $index2;
  19.             $e->post_type        = "nav_menu_item";
  20.             $e->post_status      = "published";
  21.             $e->post_parent      = $i->ID;
  22.             $e->menu_item_parent = $i->ID;
  23.             $e->type             = "custom";
  24.             $e->object           = "custom";
  25.             $e->ID               = 0;
  26.             $e->db_id            = 0;
  27.             $e->object_id        = 0;
  28.             $e->classes          = array();
  29.             $e->description      = "";
  30.             $items[]             = $e;
  31.         }
  32.     }
  33.     return $items;
  34. }, 10, 3);
也想出现在这里?联系我们
创客主机

WordPress 菜单中的分类自动添加子分类菜单

已有 203 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!