如何在Woocommerce中获取商品的最下级分类名称/别名
获取WooCommerce商品的最下级分类
要只获取商品所属的最末级分类(无下级子分类的分类),可以通过判断每个分类是否存在子分类来筛选。修改你的代码如下:
add_action('wp_head', 'get_current_product_category'); function get_current_product_category(){ global $post; if ( is_single() && 'product' === get_post_type( $post ) ) { $product_categories = wp_get_post_terms( $post->ID, 'product_cat' ); if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) { foreach ( $product_categories as $category ) { // 检查当前分类是否有子分类,无则为最末级分类 $child_categories = get_term_children( $category->term_id, 'product_cat' ); if ( empty( $child_categories ) ) { echo 'Category ID: ' . $category->term_id . '<br>'; echo 'Category Name: ' . $category->name . '<br>'; echo 'Category Slug: ' . $category->slug . '<br>'; // 如需分类别名可添加此行 } } } } }
关键说明:
get_term_children($category->term_id, 'product_cat')会返回当前分类的所有子分类ID数组,若数组为空,则说明该分类是最下级分类- 若需要输出分类别名(slug),直接启用注释的那行代码即可
- 代码仅在商品详情页执行,兼容最新版WordPress和WooCommerce
内容的提问来源于stack exchange,提问作者Classic Cars
相关产品推荐
相关产品推荐

