php - 根据 WooCommerce 中的付款方式和购物车项目总数添加费用
问题描述
我安装了一个插件->“WooCommerce 的基于支付网关的费用和折扣”,它帮助我添加了两项费用:
卡支付 14,99 送货费
货到付款 19,99 运费
问题是如果有人购买超过 300 件,我想免费送货。所以我必须取消额外费用这是我尝试过的,但没有任何反应:
function woo_remove_cart_fee() {
$cart_items_total = WC()->cart->get_cart_contents_total();
if ( $cart_items_total > 300 ) {
$fees = 0 ;
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_remove_fee' );
有任何想法吗?或者关于如何让网关费用和免费送货超过限制的任何想法?
谢谢。
解决方案
您不能删除插件根据购物车项目总安装量添加的费用。
由于您的插件不处理最小或最大购物车金额条件,请先从中禁用费用(或禁用插件)并改用以下内容:
add_action( 'woocommerce_cart_calculate_fees', 'fee_based_on_payment_method_and_total' );
function fee_based_on_payment_method_and_total( $cart ) {
if ( is_admin() && ! defined('DOING_AJAX') )
return;
$threshold_amount = 300; // Total amount to reach for no fees
$payment_method_id = WC()->session->get('chosen_payment_method');
$cart_items_total = $cart->get_cart_contents_total();
if ( $cart_items_total < $threshold_amount ) {
// For cash on delivery "COD"
if ( $payment_method_id === 'cod' ) {
$fee = 14.99;
$text = __("Fee");
}
// For credit cards (other payment gateways than "COD", "BACS" or "CHEQUE"
elseif ( ! in_array( $payment_method_id, ['bacs', 'cheque'] ) ) {
$fee = 19.99;
$text = __("Fee");
}
}
if( isset($fee) && $fee > 0 ) {
$cart->add_fee( $text, $fee, false ); // To make fee taxable change "false" to "true"
}
}
以下代码用于刷新付款方式更改的数据:
// jQuery - Update checkout on payment method change
add_action( 'wp_footer', 'custom_checkout_jquery_script' );
function custom_checkout_jquery_script() {
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'input[name="payment_method"]', function(){
$(document.body).trigger('update_checkout');
});
});
</script>
<?php
endif;
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
推荐阅读
- r - 在 R S4 中设置默认值的 setClass 中的初始化方法与原型有什么区别?
- python - 如何在 python 的逻辑回归模型中将我的预测值保存为字符串?
- mysql - SQL 多条数据同时输入
- javascript - 无法将 onclick 侦听器添加到动态创建的元素
- c# - 如何在 Mac 控制台应用程序 C# 上禁用用户输入?
- python - 使用从包运行时如何包含嵌入式控制台应用程序的依赖项
- python - (kivy)如何在不使用 RecycleView 中的空数据的情况下执行此操作?
- excel - VBA从第一个工作簿打开两个工作簿并在第二个工作簿中选择特定工作表
- php - 托管在 docker 容器中的网站未实时更新
- python - Pandas - 将列附加到 DataFrame