WooCommerce调用内置精选产品属性显示Featured标签的实现方法
正确实现方案
优先推荐使用WooCommerce原生封装的判断方法,无需手动编写Tax Query,兼容性更高:
add_action( 'woocommerce_before_single_product_summary', 'property_main_details_field', 1 ); function property_main_details_field() { global $product; // 调用WooCommerce原生方法判断当前商品是否为精选 if ( is_a( $product, 'WC_Product' ) && $product->is_featured() ) { ?> <span class="property-contract-badge">Featured</span> <?php } }
如果你希望按照你提到的Tax Query逻辑,调用echo $term->name输出术语名称实现,可以使用下方的正确写法,你此前的代码仅定义了Tax Query参数数组,没有关联当前商品做存在判断、也没有获取对应术语对象,因此无法生效:
add_action( 'woocommerce_before_single_product_summary', 'property_main_details_field', 1 ); function property_main_details_field() { global $post; // 判断当前商品是否关联了精选商品分类术语 $is_featured = has_term( 'featured', 'product_visibility', $post->ID ); if ( $is_featured ) { // 获取featured术语对象 $term = get_term_by( 'slug', 'featured', 'product_visibility' ); $badge_text = $term ? $term->name : 'Featured'; ?> <span class="property-badge"><?php echo esc_html( $badge_text ); ?></span> <?php } }
内容的提问来源于stack exchange,提问作者Ross
相关产品推荐
相关产品推荐

