如何修改WooCommerce代码仅在商品目录添加价格前置文本?
解决方案
你需要在函数中添加页面条件判断,通过WooCommerce的is_product()函数识别当前是否为商品详情页,仅在非详情页(即商品目录页)添加前置文本。
修改后的完整代码如下:
// Add text before price only on product archives function bd_rrp_price_html( $price, $product ) { // 判断当前是否为商品详情页,是则直接返回原价格 if ( is_product() ) { return $price; } // 非详情页则添加前置文本 $return_string = 'Rent from: ' . $price; return $return_string; } add_filter( 'woocommerce_get_price_html', 'bd_rrp_price_html', 100, 2 );
修改说明
- 新增
if ( is_product() )判断:该函数是WooCommerce内置的条件标签,当访问商品详情页时返回true,此时直接返回原始价格,不添加额外文本。 - 仅在非商品详情页(包括商品目录、分类页、标签页等归档页面)执行添加文本的逻辑。
内容的提问来源于stack exchange,提问作者jpopuk
相关产品推荐
相关产品推荐

