您可以使用wp_get_nav_menu_items 滤器
add_filter(\'wp_get_nav_menu_items\', \'prefix_add_categories_to_menu\', 10, 3);
然后你可以这样做:
function prefix_add_categories_to_menu($items, $menu, $args) {
// Make sure we only run the code on the applicable menu
if($menu->slug !== \'replace_this\' || is_admin()) return $items;
// Get all the product categories
$categories = get_categories(array(
\'taxonomy\' => \'product_cat\',
\'orderby\' => \'name\',
\'show_count\' => 0,
\'pad_counts\' => 0,
\'hierarchical\' => 1,
\'hide_empty\' => 1,
\'depth\' => $depth,
\'title_li\' => \'\',
\'echo\' => 0
));
$menu_items = array();
// Create menu items
foreach($categories as $category) {
$new_item = (object)array(
\'ID\' => intval($category->term_id),
\'db_id\' => intval($category->term_id),
\'menu_item_parent\' => intval($category->category_parent),
\'post_type\' => "nav_menu_item",
\'object_id\' => intval($category->term_id),
\'object\' => "product_cat",
\'type\' => "taxonomy",
\'type_label\' => __("Product Category", "textdomain"),
\'title\' => $category->name,
\'url\' => get_term_link($category),
\'classes\' => array()
);
array_push($menu_items, $new_item);
}
$menu_order = 0;
// Set the order property
foreach ($menu_items as &$menu_item) {
$menu_order++;
$menu_item->menu_order = $menu_order;
}
unset($menu_item);
return $menu_items;
}
您可以在WordPress中创建一个菜单,然后在函数顶部设置slug,以确保它只在适用的菜单上运行。然后,此功能将用您的所有产品类别替换该菜单中的任何项目。
如果你有大量的类别,我建议使用一个瞬态缓存这个菜单,例如,每天只重新生成一次。