php 在Woocommerce中隐藏基于产品类别的运输方法

j9per5c4  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(121)

与Woocommerce,我想隐藏所有的运输方法,除了“本地皮卡”当一个定义的产品类别是在购物车...
下面的代码对其他产品类型(变量产品除外)执行此操作:

add_filter( 'woocommerce_package_rates', 'custom_shipping_methods', 100, 2 );
function custom_shipping_methods( $rates, $package ){

    // Define/replace here your correct category slug (!)
    $cat_slug = 'my_category_slug';
    $prod_cat = false;

    // Going through each item in cart to see if there is anyone of your category
    foreach ( WC()->cart->get_cart() as $values ) {
        $product = $values['data'];

        // compatibility with WC +3
        $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

        if ( has_term( $cat_slug, 'product_cat', $product_id ) )
            $prod_cat = true;
    }

    $rates_arr = array();

    if ( $prod_cat ) {
        foreach($rates as $rate_id => $rate) { // <== There was a mistake here
            if ('local_pickup' === $rate->method_id) {
                $rates_arr[ $rate_id ] = $rate;
            }
        }
    }
    return !empty( $rates_arr ) ? $rates_arr : $rates;
}

我能做些什么来使它也适用于可变产品?任何帮助都很感激。

s6fujrry

s6fujrry1#

我已经重新访问了你的代码,这里是正确的方法,使它也适用于变量产品:

add_filter( 'woocommerce_package_rates', 'product_category_hide_shipping_methods', 90, 2 );
function product_category_hide_shipping_methods( $rates, $package ){

    // HERE set your product categories in the array (IDs, slugs or names)
    $categories = array( 'clothing');
    $found = false;

    // Loop through each cart item Checking for the defined product categories
    foreach( $package['contents'] as $cart_item ) {
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
            $found = true;
            break;
        }
    }

    $rates_arr = array();
    if ( $found ) {
        foreach($rates as $rate_id => $rate) { 
            if ('local_pickup' === $rate->method_id) {
                $rates_arr[ $rate_id ] = $rate;
            }
        }
    }
    return !empty( $rates_arr ) ? $rates_arr : $rates;
}
  • 代码放在你的活动子主题(或活动主题)的function.php文件中。* 测试和工作。
    需要刷新发货缓存:

1)首先,这段代码已经保存在function.php文件中。
2)在发货设置中,输入发货区域,关闭发货方式并保存,然后重新启用发货方式并保存,完成。

相关问题