Cách để 1 sản phẩm WooCommerce chỉ hiển thị 1 danh mục chính 2025
Thêm đoạn filter này vào functions.php
(theme con) để WooCommerce chỉ in ra 1 danh mục (danh mục chính).
// Chỉ hiển thị 1 danh mục cho sản phẩm trên trang chi tiết
add_filter(‘get_the_terms’, function ($terms, $post_id, $taxonomy) {
// Chỉ áp dụng cho trang single product và taxonomy product_cat
if ($taxonomy !== ‘product_cat’ || !function_exists(‘is_product’) || !is_product()) {
return $terms;
}
if (!is_array($terms) || empty($terms)) {
return $terms;
}// Ưu tiên Primary Category của Rank Math (nếu có)
$primary = null;
if (function_exists(‘rank_math_get_primary_term’)) {
$p = rank_math_get_primary_term(‘product_cat’, $post_id);
if ($p instanceof WP_Term) {
$primary = $p;
}
}// Fallback: lấy term cha cao nhất (root). Nếu không có, lấy term đầu tiên
if (!$primary) {
foreach ($terms as $t) {
if ((int) $t->parent === 0) { $primary = $t; break; }
}
if (!$primary) { $primary = reset($terms); }
}// Trả về mảng chỉ chứa 1 term
return [$primary];
}, 20, 3);// (Giữ thêm filter dưới để cover trường hợp theme có dùng wc_get_product_category_list)
add_filter(‘woocommerce_product_get_categories’, function ($html, $product) {
$pid = is_object($product) ? $product->get_id() : absint($product);
if (!$pid) return $html;$term = null;
if (function_exists(‘rank_math_get_primary_term’)) {
$p = rank_math_get_primary_term(‘product_cat’, $pid);
if ($p instanceof WP_Term) $term = $p;
}
if (!$term) {
$terms = get_the_terms($pid, ‘product_cat’);
if (is_array($terms) && !empty($terms)) {
foreach ($terms as $t) { if ((int)$t->parent === 0) { $term = $t; break; } }
if (!$term) $term = reset($terms);
}
}
if (!$term) return $html;$link = get_term_link($term);
if (is_wp_error($link)) return $html;
return sprintf(‘<a href=”%s”>%s</a>’, esc_url($link), esc_html($term->name));
}, 10, 2);
Sau khi lưu lại thì đây là kết quá !