从 WordPress 菜单隐藏 WooCommerce 空产品类别

问题描述

根据我上一个问题的 Sort WooCommerce product category sub menu items by name ASC in Wordpress menu 答案代码,我能够在我的 wordpress 导航菜单自动将子子类别显示为某些产品类别的菜单子项。

我的问题是:是否可以隐藏空子类别(子菜单项)

如果可能的话,可能隐藏只包含一种售罄产品的类别。

解决方法

您可以使用 get_terms() ,在这里您可以指定更多选项,所以

get_term_children( $post->object_id,$taxonomy );

会变成

get_terms(array(
  'taxonomy' => $taxonomy,'parent' => $post->object_id,'hide_empty' => true,));

这也有一个'order_by'参数,默认为一个术语的名称

,

您可以额外使用带有以下参数的 get_terms()

  • 'include' 包含 get_term_children() 函数中的所有子术语,作为术语 ID 的逗号分隔字符串。
  • 'orderby' 带有 'name' 属性以按名称对术语进行排序,
  • 'order' 带有 'ASC' 属性以对术语进行升序排序,
  • 'hide_empty' 带有 true 属性以不包含空术语。

因此排序将直接进行,无需 foreach 循环,您还将直接获得 WP_Term 对象数组。

重新访问的代码:

add_filter( 'wp_get_nav_menu_items','custom_submenu_product_categories',10,3 );
function custom_submenu_product_categories( $items,$menu,$args ) {
    // don't add child categories in administration of menus
    if (is_admin()) {
        return $items;
    }

    $taxonomy = 'product_cat';

    foreach ($items as $index => $post) {

        if ( $taxonomy !== $post->object ) {
            continue;
        }

        $children_terms_ids = get_term_children( $post->object_id,$taxonomy );

        if( ! empty($children_terms_ids) ) {
            $sorted_terms       = get_terms(array(
                'taxonomy'   => $taxonomy,'include'    => implode(',',$children_terms_ids),'orderby'    => 'name','order'      => 'ASC',));

            // Loop through sorted child terms to set them as sorted sub menu items
            foreach ( $sorted_terms as $index2 => $child_term ) {
                $item = new \stdClass();

                $item->title            = $child_term->name;
                $item->url              = get_term_link( $child_term,$taxonomy );
                $item->menu_order       = 500 * ($index + 1) + $index2;
                $item->post_type        = 'nav_menu_item';
                $item->post_status      = 'published';
                $item->post_parent      = $post->ID;
                $item->menu_item_parent = $post->ID;
                $item->type             = 'custom';
                $item->object           = 'custom';
                $item->description      = '';
                $item->object_id        = 0;
                $item->db_id            = 0;
                $item->ID               = 0;
                $item->position         = 0;
                $item->classes          = array();
                $item->target           = ''; // <= Missing - Mandatory to avoid an error
                $item->xfn              = ''; // <= Missing - Mandatory to avoid an error

                $items[] = $item;
            }
        }
    }
    return $items;
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。

抱歉,现在无法隐藏仅包含一种已售罄产品的子类别。