如何根据Woocommerce中的付款方式更改运输区域?

时间:2019-05-25 20:26:55

标签: php wordpress woocommerce hook-woocommerce

目标:我想根据用户的个人识别码为不同的支付网关添加不同的运输费用。

尝试使用运输区域:

我的woo-commerce仪表板中添加了3个不同的运输区域。所有区域均使用城市和统一费率的密码创建。但是,如果该密码存在于多个区域中,则在结帐页面上,顶层区域将具有优先权,而所有其他区域将被忽略。

现在,我想根据Payment Gateway用户选择的来更改该区域。例如,用户“ A”的PIN码为“ 123456”,并且此PIN码存在于两个运输区域中:“ SH1”,“ SH2”。因此,如果用户选择“货到付款”选项,那么我想在激活“ SH2”时为其禁用运输区域“ SH1”。

这是我尝试的代码,但是不起作用。

add_filter( 'woocommerce_available_payment_gateways', 'change_user_zone', 20, 1);
function change_user_zone(  $gateways ){

    $targeted_zones_names = array('COD FCity'); // Targeted zone names
    $current_payment_gateway = WC()->session->get('chosen_payment_method'); // Selected payment gateway

    // Current zone name
    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
    $chosen_method     = explode(':', reset($chosen_methods) );
    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
    $current_zone_name = $shipping_zone->get_zone_name();

    if($current_payment_gateway === "cod" && $current_zone_name === "COD FCity"){
        $WC_Shipping_Zone = new WC_Shipping_Zone();
        $var = $WC_Shipping_Zone->set_zone_locations( "India - Maharashtra - Mumbai" );
    }

    return $gateways;
}

请帮助!

注意:我正在寻找一种编码解决方案。如果您想为此建议任何插件,请使用注释部分。

1 个答案:

答案 0 :(得分:0)

好的,我找不到改变运输区域的方法。因此,我在购物车中添加了额外的费用,具体取决于“付款网关”和“运送地区”。

add_filter( 'woocommerce_before_calculate_totals', 'update_the_cart_with_extra_fee');
function update_the_cart_with_extra_fee(){
    global $woocommerce;  
    $targeted_zones_names = array('SH1'); // Targeted zone names
    $current_payment_gateway = WC()->session->get('chosen_payment_method'); // Selected payment gateway

    // Current zone name
    $chosen_methods    = WC()->session->get( 'chosen_shipping_methods' ); // The chosen shipping mehod
    $chosen_method     = explode(':', reset($chosen_methods) );
    $shipping_zone     = WC_Shipping_Zones::get_zone_by( 'instance_id', $chosen_method[1] );
    $current_zone_name = $shipping_zone->get_zone_name();

    if($current_payment_gateway === "cod" && $current_zone_name === "SH1"){
        $extra_shipping_cost = 0;  
        //Loop through the cart to find out the extra costs  
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {  
            //Get the product info  
            $_product = $values['data'];  

            //Get the custom field value - make sure it's i.e. 10 not $10.00  
            $custom_shipping_cost = 60; 


            //Adding together the extra costs 
            $extra_shipping_cost = $extra_shipping_cost + $custom_shipping_cost;

            $woocommerce->cart->add_fee( __('Cash on Delivery', 'woocommerce'), $extra_shipping_cost ); // Place this outside of foreach loop if you want to add fee for every product in the cart.
        }  
    }

}

我希望这会对某人有所帮助。