我正在尝试在 Woocommerce 中的当前类别下显示子类别(而不是子子类别等),如下所示 Web:http://www.qs-adhesivos.es/app/productos/productos.asp?idioma=en
例如,建筑是类别,密封剂和粘合剂、防水 Material 、聚氨酯泡沫……是子类别。
密封剂和胶粘剂是类别,ACETIC SILICONE SEALANT、NEUTRAL SILICONE SEALANT、ACRYLIC SEALANT……是子类别……
我的子主题下的 woocommerce 文件夹中已经有一个 archive-product.php。
已经尝试了一些代码并且它适用,但这不是我想要的。
以下代码将显示产品类别存档页面的当前产品类别中格式化的链接产品子类别:
if ( is_product_category() ) {
$term_id = get_queried_object_id();
$taxonomy = 'product_cat';
// Get subcategories of the current category
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => true,
'parent' => get_queried_object_id()
]);
$output = '<ul class="subcategories-list">';
// Loop through product subcategories WP_Term Objects
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $taxonomy );
$output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';
}
echo $output . '</ul>';
}
测试和工作。
使用示例:
1) 你可以直接在archive-product.php
中使用这段代码模板文件。
2) 您可以将代码嵌入函数中,替换最后一行 echo $output . '</ul>';
通过 return $output . '</ul>';
,对于短代码,始终返回显示。
3) 您可以使用类似 woocommerce_archive_description
的操作 Hook 嵌入代码:
// Displaying the subcategories after category title
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );
function display_subcategories_list() {
if ( is_product_category() ) {
$term_id = get_queried_object_id();
$taxonomy = 'product_cat';
// Get subcategories of the current category
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => true,
'parent' => $term_id
]);
echo '<ul class="subcategories-list">';
// Loop through product subcategories WP_Term Objects
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $taxonomy );
echo '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>';
}
echo '</ul>';
}
}
代码进入事件子主题(或事件主题)的 functions.php 文件。经过测试并有效。
要在类别描述之后显示它,请将 Hook 优先级从 5
更改为 到 20
在:
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );
喜欢:
add_action('woocommerce_archive_description', 'display_subcategories_list', 20 );