如何根据商品数量和特定类别禁用送货方式 [英] How to disable shipping method based on item count and a certain category

查看:75
本文介绍了如何根据商品数量和特定类别禁用送货方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种有选择地禁用两种运输方式的方法

I have been looking for a way to condtionally disable two shipping methods

  • 餐桌费率
  • 距离率

基于项目数.

按项目计数"我不是指数量,而是指购物车中有多少种不同的产品.购物车中的IE 2灯和3个表的项目计数为2,总数量为5.

By item count I do not mean quantity, I mean how many different products are in the cart. IE 2 Lamps and 3 tables in the cart would be an item count of 2 and a combined quantity of 5.

我还要确保此规则仅对特定类别有效.

I would also like to ensure this rule is in effect for a certain category only.

我尝试过:

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 );

推荐答案

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

You could use the following, explanation with comments added in the code

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

Conditions that must be met in this code are:

  • 购物车中至少有3个订单项
  • 1个或更多产品属于'categorie-1'类别
  • 如果满足前两个条件,则
  • 'distance_rate'和/或'table_rate'未设置
  • At least 3 line items in cart
  • 1 or more products belong to the 'categorie-1' category
  • 'distance_rate' and/or 'table_rate' become unset if the previous 2 conditions are met
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 );

这篇关于如何根据商品数量和特定类别禁用送货方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆