如果在 Woocommerce 中应用了特定的优惠券,则更改固定费率运输方式成本

Change Flat rate shipping method cost if a specific coupon is applied in Woocommerce

我有一张特定的优惠券 special50。当有人在商店应用此优惠券时,需要添加新的送货方式。当当前送货方式价格为 50 美元(统一费率)并且应用优惠券新送货方式后,定价为 25 美元。总之,如果您使用此优惠券,您将获得产品 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 );
    }

这可以使用 woocommerce_package_rates 过滤器挂钩中的以下自定义函数来完成,无需创建额外的折扣固定费率。以下代码将在应用 'special50' 优惠券时更改 "flat rate" 送货方式成本。

You should first "Enable debug mode" in Woocommerce settings > shipping > Shipping options.

代码:

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;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

Dont forget to disable "Enable debug mode" once this has been tested and works.