Trong WooCommerce 9.9.3, một vấn đề phổ biến là các Parent Category (danh mục cha) không hiển thị trên trang cửa hàng nếu chúng không chứa sản phẩm trực tiếp, ngay cả khi có các Subcategory (danh mục con) chứa sản phẩm. Đây là hành vi mặc định của WooCommerce, nhưng có thể được khắc phục bằng cách tùy chỉnh cấu hình hoặc sử dụng code. Dưới đây là hướng dẫn chi tiết để giải quyết vấn đề này.
Hướng dẫn khắc phục lỗi Parent Category không hiển thị khi không có sản phẩm trong WooCommerce 9.9.3
Bạn chỉ cần copy đoạn code sau vào file function.php là sẽ giải quyết được vấn đề:
remove_filter( 'woocommerce_product_loop_start', 'woocommerce_maybe_show_product_subcategories' );
add_action('woocommerce_shop_loop', 'nguyenlan_fix_categories', 10);
function nguyenlan_fix_categories( $args = array() ) {
$args = wp_parse_args(
$args,
array(
'before' => apply_filters( 'woocommerce_before_output_product_categories', '' ),
'after' => apply_filters( 'woocommerce_after_output_product_categories', '' ),
'parent_id' => 0,
)
);
$terms_all = get_terms(array(
'taxonomy' => 'product_cat',
'parent' => $args['parent_id'],
'hide_empty' => false,
));
$product_categories = array();
foreach ( $terms_all as $term ) {
if ( $term->count > 0 ) {
$product_categories[] = $term;
} else {
$children = get_terms(array(
'taxonomy' => 'product_cat',
'parent' => $term->term_id,
'hide_empty' => true,
'fields' => 'ids',
));
if ( ! empty($children) ) {
$product_categories[] = $term;
}
}
}
if ( empty( $product_categories ) ) {
return false;
}
echo $args['before'];
foreach ( $product_categories as $category ) {
wc_get_template(
'content-product_cat.php',
array(
'category' => $category,
)
);
}
echo $args['after'];
return true;
}
In WooCommerce 9.9.3, a common issue is that Parent Categories do not display on the shop page if they do not contain products directly, even if there are Subcategories containing products. This is the default behavior of WooCommerce, but can be fixed by customizing the configuration or using code. Here is a detailed guide to solve this problem.
Just copy the code above in the Vietnamese version of the guide into the function file and it will be solved.