[英]Change Flat rate shipping method cost if a specific coupon is applied in Woocommerce
I have a specific coupon which is special50
.我有一张
special50
的特定优惠券。 When someone applied this coupon on the store then a new shipping method need to add.当有人在商店应用此优惠券时,需要添加新的送货方式。 When current shipping method price is $50 (flat rate) and after applying coupon new shipping method, pricing will be $25.
当当前送货方式价格为 50 美元(固定费率)并且应用优惠券新送货方式后,定价为 25 美元。 In a word, if you apply this coupon you will receive 50% OFF on products(which WooCommerce has already provided to us) and 50% OFF on shipping(which really I need).
总之,如果您应用此优惠券,您将获得 50% 的产品折扣(WooCommerce 已经提供给我们)和 50% 的运费折扣(我真的需要)。
add_action( 'woocommerce_flat_rate_shipping_add_rate', 'add_another_custom_flat_rate', 10, 2 );
function add_another_custom_flat_rate( $method, $rate ) {
$new_rate = $rate;
$new_rate['id'] .= ':' . 'custom_rate_name';
$new_rate['label'] = 'Shipping and handling';
global $woocommerce, $wpdb;
$coupon = "SELECT post_title FROM {$wpdb->posts} WHERE post_title='special50' AND post_type ='shop_coupon' AND post_status ='publish'";
if(in_array($coupon_id, $woocommerce->cart->applied_coupons)){
$cost = 25;
}
$new_rate['cost'] = $cost;
$method->add_rate( $new_rate );
}
This can be done using the following custom function hooked in woocommerce_package_rates
filter hook, without any need of creating an additional discounted flat rate.这可以使用以下自定义 function 挂钩在
woocommerce_package_rates
过滤器挂钩中来完成,无需创建额外的折扣固定费率。 The following code will change the "flat rate" shipping method cost when 'special50' coupon is applied.以下代码将在应用“special50”优惠券时更改“统一费率”运输方式成本。
You should first "Enable debug mode" in Woocommerce settings > shipping > Shipping options.
您应该首先在 Woocommerce 设置 > 运输 > 运输选项中“启用调试模式” 。
The code:代码:
add_filter('woocommerce_package_rates', 'coupon_discount_on_flat_rate', 10, 2);
function coupon_discount_on_flat_rate( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// Checking for 'special50' in applied coupons
if( in_array( 'special50', WC()->cart->get_applied_coupons() ) ){
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Targeting "flat rate" shipping method
if( $rate->method_id === 'flat_rate' ){
// Set 50% of the cost
$rates[$rate_key]->cost = $rates[$rate_key]->cost / 2;
// Taxes rate cost (if enabled)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
$has_taxes = true;
// set 50% of the cost
$taxes[$key] = $rates[$rate_key]->taxes[$key] / 2;
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
}
return $rates;
}
Code goes in function.php file of your active child theme (or active theme).代码进入您的活动子主题(或活动主题)的 function.php 文件。 Tested and works.
测试和工作。
Dont forget to disable "Enable debug mode" once this has been tested and works.
一旦经过测试并工作,不要忘记禁用“启用调试模式” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.