以下代码将显示产品类别存档页面当前产品类别中格式化的链接产品子类别:
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>';
by return $output . '</ul>';
,对于短代码,总是返回显示。
3)您可以使用操作挂钩嵌入代码,例如woocommerce_archive_description
:
// 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 文件中。经过测试并有效。
要在类别描述之后显示它,请将挂钩优先级从5
to 20
in:
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );
like:
add_action('woocommerce_archive_description', 'display_subcategories_list', 20 );