WooCommerce Conditional Shipping Zone Selection for Each Product Individually

时间:2017-12-18 05:42:02

标签: php wordpress woocommerce shipping hook-woocommerce

I am using WooCommerce 3.2.6 and Thing I want to achieve is I want to setup Different Shipping Zone for Each Individual Product.

I have products which needs shipping rate calculated based upon custom box dimensions and I am using FEDEX API for rates calculation. To achieve this, I need some piece of code or Filter By Which I may setup Different Shipping Zone only to specific product.

Here's some piece of code by which I was able to MAP the Product with Shipping Zone, but then I couldn't proceed next to actually SET only that SHIPPING ZONE to bring and show rates in frontend of website. Any help would be highly Appreciated.

add_action('wp_head','show_only_selected_zone', 2, 10);
function show_only_selected_zone() {

//if(is_product) {
global $post;
$product_id = get_the_ID();
$product_name = get_the_title( $product_id );
$explode_product = explode(" ",$product_name);

        $all_zones = orig_get_all_zones();

        foreach ($all_zones as $key => $zone) {
            //echo "<pre>";print_r($zone);echo "</pre>";
            $extracted_zone = $zone['zone_name'];
            $zone_id = $zone['zone_id'];
            if(in_array($extracted_zone,$explode_product)) {
                //echo 'This is Extracted Zone: '.$extracted_zone. ' '. $zone_id;
                $set_zone_id = $zone_id;
                echo $set_zone_id;
                $zone = WC_Shipping_Zones::set_zone_by( 'zone_id', $set_zone_id );
                //echo 'Zone Result May be: '.$zone;
                break;
            }

        //echo "<pre>";print_r($zone);echo "</pre>";
        //echo $zone['zone_name'].'<br>';
        }

}


function orig_get_all_zones() {
if( class_exists( 'WC_Shipping_Zones' ) ) {
    $all_zones = WC_Shipping_Zones::get_zones();
    return $all_zones;
}
return false;
}
function orig_get_zone( $zone_id = 0 ) {
if( class_exists( 'WC_Shipping_Zones' ) ) {
    $the_zone = WC_Shipping_Zones::get_zone( $zone_id );
    return $the_zone;
}
return false;
}

1 个答案:

答案 0 :(得分:0)

首先,您的$zone应该是WC_Shipping_Zone没有s

$zone = WC_Shipping_Zone::set_zone_by( 'zone_id', $set_zone_id );

至于WC_Shipping_Zones class,没有任何可用的 setters 方法......

现在我认为,当您尝试(可能是我错了)时,通过发货区设置产品是不可能的。如果这是可能的,它将是一个真正的高级开发,而且对于StackOverFlow来说太宽泛了。