基于WooCommerce中所选付款方式的运费折扣



如果客户选择特定的付款方式,我目前正在尝试在运费上应用折扣。

出于某种原因,无论选择哪种支付方式,这都会应用折扣。

我在functions.php中使用的代码是:

function filter_woocommerce_package_rates( $rates, $package ) {

$min = 25;
$min2 = 25;
$max = 50;
$discount_percent = 50;
$payment_method = 'clearpay';
$chosen_payment_method = WC()->session->get('chosen_payment_method');
// Get cart total
$cart_total = WC()->cart->cart_contents_total;
// Condition
if ( $cart_total >= $min && $cart_total <= $max && $payment_method == $chosen_payment_method ) {
// (Multiple)
foreach ( $rates as $rate_key => $rate ) {
// Get rate cost            
$cost = $rates[$rate_key]->cost;

// Set rate cost
$rates[$rate_key]->cost = $cost - ( ( $cost * $discount_percent ) / 100 );
}

wc_add_notice( 
sprintf( 'Congratulations! Your shipping is now 50&#37; off!' , 
wc_price( WC()->cart->total ), 
wc_price( $minimum )
), 'success' 
);

}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
do_action( 'woocommerce_set_cart_cookies',  true );

知道怎么了吗?

这就是我所做的,以便获得不同支付方式的统一折扣金额

你可以根据你的情况调整

add_action( 'woocommerce_cart_calculate_fees','mlnc_add_discount', 20, 1 );
function mlnc_add_discount( $cart_object ) {
$label= __('');
$discount = 0;
$chosen_payment_method = WC()->session->get('chosen_payment_method'); //get the selected payment method
switch($chosen_payment_method){
case 'paypal':    
$label = __( "PayPal Discount" );
// The discount amount to apply
$discount = 5;
break;
case 'bacs':    
$label = __( "Direct Bank Transfer Discount" );
// The discount amount to apply
$discount = 10;
break; 
case 'cod':    
$label = __( "Cash on Delivery Discount" );
// The discount amount to apply
$discount = 0;
break; 
}
// Add the discount
$cart_object->add_fee( $label, - $discount, false );
}

您的代码包含不必要的变量,这些变量要么没有使用,要么使用不正确。你的问题描述中肯定没有提到。

因此,根据您可以使用的所选付款方式申请运费折扣。

function filter_woocommerce_package_rates( $rates, $package ) { 
// Payment methods - Add several if desired, separated by a comma
$payment_methods = array( 'bacs', 'clearpay' );

// Get chosen payment method
$chosen_payment_method = WC()->session->get('chosen_payment_method');

// Compare, found = continue
if ( in_array( $chosen_payment_method, $payment_methods ) ) {
// Discount percent
$discount_percent = 50;

// Loop trough
foreach ( $rates as $rate_key => $rate ) {
// Get rate cost            
$cost = $rates[$rate_key]->cost;

// Set rate cost
$rates[$rate_key]->cost = $cost - ( ( $cost * $discount_percent ) / 100 );
}   
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

注意:不要忘记清空购物车,以刷新WooCommerce运输缓存

最新更新