我们在进行 WordPress 主题开发的时候,我们会遇到子分类特别多,而且还要添加到网站导航中的情况。如果导航中只有分类还好弄,可是还有其他自定义菜单项的话,就比较麻烦了。多数时候,要手动去添加顶级分类下的子分类,很费时。下面说下,如何在菜单本身是分类的情况下,自动添加其下的子分类为子菜单。
- /* 自动给导航菜单中的分类添加其下的子分类 */
- 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) {
- continue;
- }
- $term_children = get_term_children($i->object_id, "category");
- 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->ID = 0;
- $e->db_id = 0;
- $e->object_id = 0;
- $e->classes = array();
- $e->description = "";
- $items[] = $e;
- }
- }
- return $items;
- }, 10, 3);
- 1、本站大部分内容均收集于网络,若内容侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn,我们将第一时间处理!
- 2、本站资源所需价格并非资源售卖价格,是收集、整理、编辑以及本站运营的适当补贴,并且本站不提供任何免费技术服务。
- 3、所有资源仅限参考和学习,版权归原作者所有,更多请阅读无言说网络服务器协议。