[英]How to Make a menu with product category Dynamically in wordpress
我有一个问题,我可以一键制作带有产品类别的菜单,还是在 WordPress 中动态制作菜单我有很多类别而且制作这个非常耗时
我为此找到了一个插件:
但我不知道这个工作
您可以通过强制将 WooCommerce 类别添加到特定菜单 ID 来执行此操作。
将此添加到主题的 functions.php 文件中:
function _custom_nav_menu_item( $title, $url, $order, $parent = 0 ){
$item = new stdClass();
$item->ID = 1000000 + $order + $parent;
$item->db_id = $item->ID;
$item->title = $title;
$item->url = $url;
$item->menu_order = $order;
$item->menu_item_parent = $parent;
$item->type = '';
$item->object = '';
$item->object_id = '';
$item->classes = array();
$item->target = '';
$item->attr_title = '';
$item->description = '';
$item->xfn = '';
$item->status = '';
return $item;
}
add_filter("wp_get_nav_menu_items", function ($items, $menu, $args) {
if( $menu->term_id != 24 ) return $items; // Where 24 is Menu ID, so the code won't affect other menus.
// don't add child categories in administration of menus
if (is_admin()) {
return $items;
}
$ctr = ($items[sizeof($items)-1]->ID)+1;
foreach ($items as $index => $i)
{
if ("product_cat" !== $i->object) {
continue;
}
$menu_parent = $i->ID;
$terms = get_terms( array('taxonomy' => 'product_cat', 'parent' => $i->object_id ) );
foreach ($terms as $term) {
$new_item = _custom_nav_menu_item( $term->name, get_term_link($term), $ctr, $menu_parent );
$items[] = $new_item;
$new_id = $new_item->ID;
$ctr++;
$terms_child = get_terms( array('taxonomy' => 'product_cat', 'parent' => $term->term_id ) );
if(!empty($terms_child))
{
foreach ($terms_child as $term_child)
{
$new_child = _custom_nav_menu_item( $term_child->name, get_term_link($term_child), $ctr, $new_id );
$items[] = $new_child;
$ctr++;
}
}
}
}
return $items;
}, 10, 3);
在上面的代码中注意$menu->term_id != 24
部分。 然后用您的菜单 ID 更改24
的值。
上面的代码还将排除空的产品类别。
还有一个插件可以做同样的事情,而不仅仅是产品类别: https://wordpress.org/plugins/jc-submenu/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.