我们在进行 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);
专业提供WordPress主题安装、深度汉化、加速优化等各类网站建设服务,详询在线客服!