如何修改代码让WooCommerce产品归档页重量属性显示在加购按钮前?
解决方案
要将重量属性显示在「加入购物车」按钮之前,你需要替换触发钩子为woocommerce_before_shop_loop_item_add_to_cart——这个钩子的执行时机恰好位于加入购物车按钮渲染之前。修改后的代码如下:
add_action( 'woocommerce_before_shop_loop_item_add_to_cart', 'rs_show_weights', 10 ); function rs_show_weights() { global $product; // 确保产品对象存在且包含重量属性 if ( ! is_a( $product, 'WC_Product' ) || ! $product->has_weight() ) { return; } $weight = $product->get_weight(); $weight_unit = get_option('woocommerce_weight_unit'); echo '<div class="product-meta"><span class="product-meta-label">重量: </span>' . esc_html( $weight ) . esc_html( $weight_unit ) . '</div>'; }
关键修改说明
- 替换原钩子
woocommerce_after_shop_loop_item为woocommerce_before_shop_loop_item_add_to_cart,直接精准控制内容显示位置 - 添加
is_a()检查,避免产品对象不存在时触发错误 - 使用
esc_html()对输出内容转义,提升站点安全性 - 移除多余的
</br>标签,建议通过CSS类控制间距,样式调整更灵活
内容的提问来源于stack exchange,提问作者isholacode
相关产品推荐
相关产品推荐

