WordPress+WooCommerce商城:指定支付方式下移除商品折扣需求
解决WooCommerce指定支付方式下移除商品折扣的问题
由于你的商品折扣是通过_sale_price字段单独设置的不同比例,无法用固定比例调整,我们可以通过前端监听支付方式选择+后端动态替换价格的方案实现需求:当用户选择wc_tinkoff_kvk支付方式时,商品自动恢复原价,其他支付方式保留促销价。
实现步骤
1. 前端监听支付方式选择并同步状态
添加以下JavaScript代码到你的主题或自定义脚本中,用于监听用户选择的支付方式,并触发价格更新:
jQuery(document).ready(function($) { // 监听支付方式切换 $('form.checkout').on('change', 'input[name="payment_method"]', function() { const selectedPayment = $(this).val(); // 把选中的支付方式存入sessionStorage sessionStorage.setItem('selected_payment', selectedPayment); // 触发结算页面价格更新 $('body').trigger('update_checkout'); }); // 页面刷新后恢复之前选中的支付方式 const savedPayment = sessionStorage.getItem('selected_payment'); if (savedPayment && $(`input[name="payment_method"][value="${savedPayment}"]`).length) { $(`input[name="payment_method"][value="${savedPayment}"]`).prop('checked', true); } });
2. 后端动态过滤商品价格
将以下PHP代码添加到主题的functions.php文件,或使用Code Snippets插件管理:
// 过滤商品价格,针对指定支付方式移除折扣 add_filter('woocommerce_product_get_sale_price', 'remove_sale_for_tinkoff_kvk', 10, 2); add_filter('woocommerce_product_get_price', 'remove_sale_for_tinkoff_kvk', 10, 2); // 针对可变商品的子变体 add_filter('woocommerce_product_variation_get_sale_price', 'remove_sale_for_tinkoff_kvk', 10, 2); add_filter('woocommerce_product_variation_get_price', 'remove_sale_for_tinkoff_kvk', 10, 2); function remove_sale_for_tinkoff_kvk($price, $product) { // 仅在购物车和结算页面生效 if (!is_cart() && !is_checkout()) { return $price; } // 获取当前选中的支付方式 $selected_payment = ''; // 结算提交时从POST获取 if (isset($_POST['payment_method'])) { $selected_payment = sanitize_text_field($_POST['payment_method']); } // 页面加载时从session获取 elseif (WC()->session) { $selected_payment = WC()->session->get('selected_payment_method'); } // 如果选中wc_tinkoff_kvk,返回商品原价 if ($selected_payment === 'wc_tinkoff_kvk') { return $product->get_regular_price(); } return $price; } // 同步支付方式到WooCommerce会话 add_action('woocommerce_checkout_update_order_review', 'sync_payment_to_session'); function sync_payment_to_session($post_data) { parse_str($post_data, $data); if (isset($data['payment_method']) && WC()->session) { WC()->session->set('selected_payment_method', sanitize_text_field($data['payment_method'])); } }
注意事项
- 代码仅在购物车和结算页面生效,不会影响商品详情页的价格展示。
- 可变商品的子变体也会被正确处理,确保所有类型商品都能恢复原价。
- 建议使用Code Snippets插件添加PHP代码,避免主题更新导致代码丢失。
内容的提问来源于stack exchange,提问作者Эдуард Белокрылов
相关产品推荐
相关产品推荐

