WooCommerce Premium用户角色折扣与免费商品配置问题求助
问题分析与修正方案
你的代码存在几个关键问题:
- 用商品名称判断产品极易失效(比如修改名称就会破功),应该用产品ID/SKU替代
- Candle的逻辑完全搞反了——你写的是移除购物车中的Candle,但需求是让Premium用户免费获得它
- Wall Picture用
add_fee添加折扣会单独显示费用,而非直接修改商品单价,导致商品页和购物车价格不一致 - 缺少自动添加免费Candle到购物车的逻辑
下面是修正后的完整代码,同时满足所有需求:
// 1. 商品页显示折扣价/免费标签 function custom_product_price_display( $price, $product ) { // 非Premium用户直接返回原价 if ( ! is_user_logged_in() || ! in_array( 'premium', wp_get_current_user()->roles ) ) { return $price; } // 替换成你实际的产品ID(从产品编辑页URL获取) $wall_picture_id = 123; $candle_id = 456; // Wall Picture 显示9折+原价划掉 if ( $product->get_id() === $wall_picture_id ) { $discounted_price = $product->get_regular_price() * 0.9; return wc_price( $discounted_price ) . ' <del>' . wc_price( $product->get_regular_price() ) . '</del>'; } // Candle 显示"免费" if ( $product->get_id() === $candle_id ) { return __('免费', 'woocommerce'); } return $price; } add_filter( 'woocommerce_get_price_html', 'custom_product_price_display', 20, 2 ); // 2. 购物车/结算页直接调整商品价格 function custom_cart_price_adjustments( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // 非Premium用户跳过 if ( ! is_user_logged_in() || ! in_array( 'premium', wp_get_current_user()->roles ) ) return; $wall_picture_id = 123; $candle_id = 456; foreach ( $cart->get_cart() as $cart_item ) { $product = $cart_item['data']; // Wall Picture 应用10%折扣 if ( $product->get_id() === $wall_picture_id ) { $product->set_price( $product->get_regular_price() * 0.9 ); } // Candle 设置为0元 if ( $product->get_id() === $candle_id ) { $product->set_price( 0 ); } } } add_action( 'woocommerce_before_calculate_totals', 'custom_cart_price_adjustments', 20 ); // 3. Premium用户添加Wall Picture时自动赠送Candle function auto_add_free_candle_to_cart( $cart_item_key, $product_id, $quantity ) { // 非Premium用户跳过 if ( ! is_user_logged_in() || ! in_array( 'premium', wp_get_current_user()->roles ) ) return; $wall_picture_id = 123; $candle_id = 456; // 仅当添加的是Wall Picture时触发 if ( $product_id !== $wall_picture_id ) return; // 检查购物车是否已有Candle,避免重复添加 $candle_in_cart = false; foreach ( WC()->cart->get_cart() as $item ) { if ( $item['product_id'] === $candle_id ) { $candle_in_cart = true; break; } } // 没有则添加免费Candle if ( ! $candle_in_cart ) { WC()->cart->add_to_cart( $candle_id ); } } add_action( 'woocommerce_add_to_cart', 'auto_add_free_candle_to_cart', 10, 3 );
使用说明
- 替换产品ID:把代码里的
123和456换成你实际的Wall Picture和Candle的产品ID(在产品编辑页的URL里能找到,比如post=123) - 添加代码:可以把代码放到主题的
functions.php文件,或者用Code Snippets这类插件添加(推荐后者,避免主题更新丢失代码) - 测试场景:切换到Premium用户角色,测试:
- 打开Wall Picture商品页,确认显示折扣价+原价划掉
- 添加Wall Picture到购物车,确认自动加入免费Candle
- 打开Candle商品页,确认显示“免费”
- 查看购物车和结算页,确认价格正确
内容的提问来源于stack exchange,提问作者Simen
相关产品推荐
相关产品推荐

