最下级分类显示它的上一级的所有同级分类缩略图+名称
// 在产品分类页产品列表前,显示子分类(如果有),否则显示上一级分类的所有同级分类
add_action( ‘woocommerce_before_shop_loop’, ‘cc_display_category_box’, 5 );
function cc_display_category_box() {
if ( ! is_product_category() ) return; // 仅在产品分类页生效
$current_cat = get_queried_object();
if ( ! $current_cat || empty( $current_cat->term_id ) ) return;
// 1. 获取当前分类的子分类
$subcats = get_terms( array(
‘taxonomy’ => ‘product_cat’,
‘parent’ => $current_cat->term_id,
‘hide_empty’ => true,
‘orderby’ => ‘menu_order’,
‘order’ => ‘ASC’,
) );
if ( ! empty( $subcats ) && ! is_wp_error( $subcats ) ) {
// 👉 当前分类有子分类 → 显示子分类缩略图
echo ‘
-
- ‘;
-
- foreach ( $subcats as $cat ) {
-
- $thumb_id = get_term_meta( $cat->term_id, ‘thumbnail_id’, true );
-
- $thumb_url = $thumb_id ? wp_get_attachment_image_url( $thumb_id, ‘thumbnail’ ) : wc_placeholder_img_src();
-
- $link = get_term_link( $cat );
echo ‘
‘;
}
echo ‘
‘;
} else {
// 👉 当前分类没有子分类 → 显示它上一级分类的所有子分类(即同级分类们)
if ( $current_cat->parent ) {
$siblings = get_terms( array(
‘taxonomy’ => ‘product_cat’,
‘parent’ => $current_cat->parent,
‘hide_empty’ => true,
‘orderby’ => ‘menu_order’,
‘order’ => ‘ASC’,
) );
if ( ! empty( $siblings ) && ! is_wp_error( $siblings ) ) {
echo ‘
-
- ‘;
-
- foreach ( $siblings as $cat ) {
-
- $thumb_id = get_term_meta( $cat->term_id, ‘thumbnail_id’, true );
-
- $thumb_url = $thumb_id ? wp_get_attachment_image_url( $thumb_id, ‘thumbnail’ ) : wc_placeholder_img_src();
-
- $link = get_term_link( $cat );
echo ‘
‘;
}
echo ‘
‘;
}
}
}
}