php 如何运送特定的woocommerce产品或类别为特定的航运区

j91ykkif  于 2023-03-21  发布在  PHP
关注(0)|答案(1)|浏览(147)

例如:我有3个运输区域,A区,B区,C区和3个类别,A类,B类,C类
我只想为A区运送A类,必须不能为B区和C区运送A类。
Add_filter('woocommerce_package_rates','specific_products_shipping_methods',10,2);功能特定产品运送方法($费率,$包裹){

$product_ids = array( 11909, 11907 ); // HERE set the product IDs in the array
$method_id = 'wbs:14:0dd3bc79_weight_based_shipping'; // HERE set the shipping method ID
$found = false;

// Loop through cart items Checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
    if ( in_array( $cart_item['product_id'], $product_ids ) ){
        $found = true;
        break;
    }
}
if ( $found )
    unset( $rates[$method_id] );

return $rates;

}
我尝试了这个代码

bvhaajcl

bvhaajcl1#

使用woocommerce_package_rates过滤器检查发货区域和产品类别,以删除相应的发货方式

function specific_products_shipping_methods( $rates, $package ) {
    $category_ids = [ 'cat-a' ]; 
    $zone_ids = [ 'zone-a' ]; 
    $shipping_method_ids = [ 'flat_rate:1', 'flat_rate:2' ]; 

    $found_category = false;
    $found_zone = false;

    foreach( $package['contents'] as $cart_item ) {
        if ( has_term( $category_ids, 'product_cat', $cart_item['product_id'] ) ) {
            $found_category = true;
            break;
        }
    }

    $zone = WC_Shipping_Zones::get_zone_matching_package( $package );
    if ( $zone && in_array( $zone->get_id(), $zone_ids ) ) {
        $found_zone = true;
    }

    if ( $found_category && $found_zone ) {
        foreach ( $shipping_method_ids as $shipping_method_id ) {
            unset( $rates[ $shipping_method_id ] );
        }
    }

    return $rates;
}

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );

相关问题