【问题标题】:Change Flat rate shipping method cost if a specific coupon is applied in Woocommerce如果在 Woocommerce 中应用特定优惠券,则更改统一运费方式成本
【发布时间】:2018-11-27 04:38:24
【问题描述】:

我有一张特定的优惠券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 );
    }

【问题讨论】:

    标签: php wordpress woocommerce shipping coupon


    【解决方案1】:

    这可以使用woocommerce_package_rates 过滤器挂钩中的以下自定义函数来完成,而无需创建额外的折扣统一费率。以下代码将在应用“special50”优惠券时更改“统一费率”运费。

    您应该首先在 Woocommerce 设置 > 运输 > 运输选项中“启用调试模式”

    代码:

    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 文件中。经过测试并且可以工作。

    不要忘记禁用 “启用调试模式”,一旦它经过测试并且可以工作。

    【讨论】:

    • 这是一个很好的解决方案。谢谢。
    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 2020-12-03
    • 2019-07-26
    • 2013-03-22
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多