gpt4 book ai didi

php - 根据 Woocommerce 中的产品类别隐藏运输方式

转载 作者:行者123 更新时间:2023-12-04 00:05:07 25 4
gpt4 key购买 nike

使用 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;
}

我该怎么做才能使它也适用于可变产品?任何帮助表示赞赏。

最佳答案

我已经重新访问了您的代码,这是使其也适用于可变产品的正确方法:

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 文件中。测试和工作。

You should need to refresh the shipping caches:
1) First this code is already saved on your function.php file.
2) In Shipping settings, enter in a Shipping Zone and disable a Shipping Method and "save". Then re-enable that Shipping Method and "save". You are done.

关于php - 根据 Woocommerce 中的产品类别隐藏运输方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49307885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com