基于WooCommerce购物车重量应用自定义价格及折扣展示的实现问询
实现基于购物车总重量切换自定义价格的方案
核心逻辑说明
当购物车总重量超过100kg时,所有商品启用custom_price字段值作为售价;未超过阈值时保持商品常规价格。同时计算常规总价与自定义价总价的差额,作为折扣信息展示在购物车和结算页。
代码实现
1. 切换商品价格(购物车/结算页实时生效)
将以下代码添加到主题的functions.php文件,或使用自定义代码插件执行:
add_action('woocommerce_before_calculate_totals', 'switch_price_based_on_cart_weight', 9999); function switch_price_based_on_cart_weight($cart) { if (is_admin() && !defined('DOING_AJAX')) return; if (did_action('woocommerce_before_calculate_totals') >= 2) return; // 设定重量阈值(kg) $weight_threshold = 100; // 获取当前购物车总重量 $total_weight = $cart->get_cart_contents_weight(); foreach ($cart->get_cart() as $cart_item_key => $cart_item) { $product = $cart_item['data']; // 获取产品自定义价格字段值 $custom_price = get_post_meta($product->get_id(), 'custom_price', true); if ($total_weight > $weight_threshold && !empty($custom_price)) { // 启用自定义价格 $product->set_price(floatval($custom_price)); } else { // 恢复商品常规价格 $product->set_price($product->get_regular_price()); } } }
2. 计算并展示折扣差额
添加以下代码,在购物车和结算页的订单总计区域显示重量优惠折扣:
add_action('woocommerce_cart_totals_before_order_total', 'display_weight_based_discount'); add_action('woocommerce_review_order_before_order_total', 'display_weight_based_discount'); function display_weight_based_discount() { $cart = WC()->cart; $weight_threshold = 100; $total_weight = $cart->get_cart_contents_weight(); // 未达到重量阈值时不显示折扣 if ($total_weight <= $weight_threshold) return; $regular_total = 0; $custom_total = 0; foreach ($cart->get_cart() as $cart_item) { $product = $cart_item['data']; $qty = $cart_item['quantity']; // 计算常规价格总价 $regular_total += $product->get_regular_price() * $qty; // 计算自定义价格总价 $custom_price = get_post_meta($product->get_id(), 'custom_price', true); $custom_total += (!empty($custom_price) ? floatval($custom_price) : $product->get_regular_price()) * $qty; } $discount_amount = $regular_total - $custom_total; if ($discount_amount > 0) { echo '<tr class="weight-based-discount"> <th>' . __('重量优惠折扣', 'woocommerce') . '</th> <td data-title="' . __('重量优惠折扣', 'woocommerce') . '">' . wc_price(-$discount_amount) . '</td> </tr>'; } }
3. 注意事项
- 确保产品的
custom_price字段已正确添加(可通过自定义字段插件或代码创建),字段名称需与代码中的custom_price完全一致。 - 代码会随购物车内容更新实时计算重量并切换价格,AJAX更新购物车时也会同步生效。
- 测试前建议清空购物车缓存,避免价格显示异常。
内容的提问来源于stack exchange,提问作者Nisi t
相关产品推荐
相关产品推荐

