【问题标题】:WooCommerce remove shipping method based on product IDs & quantity boughtWooCommerce 根据购买的产品 ID 和数量删除运输方式
【发布时间】:2021-03-29 09:24:28
【问题描述】:

我正在尝试根据我的购物车中的两个参数删除送货方式。 参数 1 = 产品 ID 参数 2 = 为该产品 ID 添加的数量。

我一直在搜索和组合不同的解决方案,但是使用下面的 sn-p 仍然不能给我正确的结果。预期结果是,如果任何产品(6、9、69、71)被添加到我的购物车 52 次,运费 (flexible_shipping_2_1) 应该会消失。

所有建议将不胜感激。

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {

    $product_ids = array( 6 , 9, 69 , 71 ); // HERE set the product IDs in the array
    $method_id = 'flexible_shipping_2_1'; // HERE set the shipping method ID
    $found = false;
    

    // Loop through cart items Checking for defined product IDs
    foreach( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
        if ( in_array( $cart_item['product_id'], $product_ids ) && $cart_item['quantity'] == 52){
            $found = true;
            break;
        }
    }
    if ( $found )
        unset( $rates[$method_id] );

    return $rates;
}

【问题讨论】:

  • 嗨 LoicTheAztec,感谢您在这件事上的支持和智慧,它真的帮助了我。

标签: php wordpress woocommerce shipping-method product-quantity


【解决方案1】:

也许这就是您想要的(获取所有已定义产品 ID 的累积数量)

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {

    $product_ids = array( 6 , 9, 69 , 71 ); // HERE set the product IDs in the array
    $method_id   = 'flexible_shipping_2_1'; // HERE set the shipping method ID
    $quantity    = 0;
    

    // Get cart items for the current shipping package
    foreach( $package['contents'] as $cart_item ) {
        if ( in_array( $cart_item['product_id'], $product_ids ) ){
            $quantity += $cart_item['quantity'];
        }
    }
    
    if ( $quantity >= 52 && isset($rates[$method_id]) ) {
        unset($rates[$method_id]);
    }
        

    return $rates;
}

别忘了清空您的购物车,刷新发货缓存数据……

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 2021-05-15
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 2020-08-25
    相关资源
    最近更新 更多