【问题标题】:How to disable shipping method based on item count and a certain category如何根据商品数量和特定类别禁用运输方式
【发布时间】:2020-05-08 10:48:55
【问题描述】:

我一直在寻找一种有条件地禁用两种送货方式的方法

  • 表率
  • 距离率

基于项目数。

商品数量不是指数量,而是指购物车中有多少种不同的产品。 IE 购物车中的 2 个灯和 3 个桌子的项目数为 2,总数量为 5。

我还想确保此规则仅对特定类别有效。

我试过了:

function hide_shipping_count_based( $rates, $package ) {

    // Set count variable
    $cart_count = 0;

    // Calculate cart's total
    foreach( WC()->cart->cart_contents as $key => $value) {
        $cart_count ++;
    }

    // only if the weight is over 150lbs find / remove specific carrier
    if( $cart_count > 2 ) {
        // loop through all of the available rates

        unset( $rates[ 'distance_rate' ] );
        unset( $rates[ 'table_rate' ] );

    }

    return $rates;
}

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

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce shipping-method


    【解决方案1】:

    您可以使用以下解释,并在代码中添加 cmets

    此代码中必须满足的条件是:

    • 购物车中至少有 3 个订单项
    • 1 个或多个产品属于 'categorie-1' 类别
    • 如果满足前两个条件,“distance_rate”和/或“table_rate”将变为未设置

    function hide_shipping_count_based( $rates, $package ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        // Count line items
        $count =  count( $package['contents'] );
    
        // Set variable
        $found = false;
    
        // Set term (category)
        $term = 'categorie-1';
    
        // Check count
        if( $count > 2 ) {
    
            // Loop through line items
            foreach( $package['contents'] as $line_item ) {
                // Get product id
                $product_id = $line_item['product_id'];
    
                // Check for category
                if ( has_term( $term, 'product_cat', $product_id ) ) {
                    $found = true;
                    break;
                }
            }
        }
    
        // True
        if ( $found ) {
            // Loop trough rates
            foreach ( $rates as $rate_key => $rate ) {
                // Targeting
                if ( in_array( $rate->method_id, array( 'distance_rate', 'table_rate' ) ) ) {
                    unset( $rates[$rate_key] );
                }
            }
        }
    
        return $rates;
    }
    add_filter( 'woocommerce_package_rates', 'hide_shipping_count_based', 100, 2 );
    

    【讨论】:

    • 更紧凑:if ( in_array( $rate->method_id, array( 'table_rate', 'distance_rate' ) ) ) unset($rates[$rate_key]);
    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多