[英]Hide specific shipping options based on products or categories in WooCommerce
[英]Hide shipping methods based on products categories in Woocommerce
使用 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 文件中。 測試和工作。
您應該需要刷新運輸緩存:
1) 首先,此代碼已保存在您的 function.php 文件中。
2) 在配送設置中,輸入配送區域並禁用配送方式並“保存”。 然后重新啟用該運輸方式並“保存”。 你完成了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.