我试图在Woocommerce中的当前类别下显示子类别(而不是子类别,等等),就像这个网站:http://www.qs-adhesivos.es/app/productos/productos.asp?idioma=en
例如,建筑是类别,密封剂和粘合剂,防水,聚氨酯泡沫…是子类别。
密封胶&胶粘剂是一类,而醋酸型硅酮密封胶、中性硅酮密封胶、丙烯酸类密封胶…子类别是否为…
我已经在我的孩子主题下的woocommerce文件夹中有一个archive-product.php。
我已经尝试了一些代码,它适用,但这不是我想要的。
发布于 2019-09-03 16:56:47
以下代码将显示产品类别存档页面中当前产品类别的格式化链接产品子类别:
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 )嵌入代码
// 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更改为20:
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 ); 像这样:
add_action('woocommerce_archive_description', 'display_subcategories_list', 20 ); https://stackoverflow.com/questions/57767843
复制相似问题