我需要woocommerce运输选项的帮助,我想隐藏特定产品类别的统一费率,我只想显示本地交付或本地取件选项。
对于所有其他类别,所有选项都应该工作。
我试着用这段代码(添加在我的主题的function.php文件):
function cart_has_product_with_orange_cats() {
global $woocommerce;
$product_in_cart = false;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
// second level loop search, in case some items have several categories
if($terms){
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if ( $_categoryid == 16 ) {
//category is in cart!
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
// add filter and function to hide method
add_filter( 'woocommerce_available_shipping_methods', 'custom_shipping_methods' , 10, 1 );
function custom_shipping_methods( $available_methods ){
if ( cart_has_product_with_orange_cats() ) {
foreach($available_methods as $key => $method){
if( $key == 'local_delivery' || $key == 'local_pickup'){
continue;
}
unset($available_methods[$key]);
}
// remove the rate you want
}
// return the available methods without the one you unset.
return $available_methods;
}
但它不适合我,也许是因为过时的代码为最新的WooCommerce版本或任何其他问题。
我怎样才能做到这一点?
更新 (兼容wc3 +,也适用于各种产品)
完全功能测试的和更正的代码位于另一个线程上:
运输方法-当固定费率隐藏时,本地取件选项不可用
重要提示:
woocommerce_available_shipping_methods
钩子自WC版本2.1+以来已弃用,您需要使用woocommerce_package_rates
过滤器钩子
WooCommerce 2.6+版本引入新的航运区。所以所有WooCommerce之前版本的运费相关代码都是过时的和将不再工作。
For info:
global $woocommerce;
**与$woocommerce->cart
已被WC()->cart
所取代。
您将使用WC()->cart->get_cart()
…
我们将不再需要你的自定义条件函数,因为WordPress中已经存在一个条件函数,你可以针对WooCommerce的产品类别。该函数接受术语ID、术语段符或术语名称:
has_term( 'your_category', 'product_cat', $post_id )
所以我们可以使用 has_term()
条件函数:
add_filter( 'woocommerce_package_rates', 'conditional_hide_shipping_methods', 100, 2 );
function conditional_hide_shipping_methods( $rates, $package ){
// Define/replace here your correct category slug (!)
$product_category = 'your_category';
$prod_cat = false;
// Going through each item in cart to see if there is anyone of your category
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product_id = $cart_item['product_id'];
if ( has_term( $product_category, 'product_cat', $product_id ) ){
$prod_cat = true;
}
}
$rates_arr = array();
if ( $prod_cat ) {
foreach($rates as $key => $rate) {
if ('free_shipping' === $rate->method_id || 'local_pickup' === $rate->method_id || 'local_delivery' === $rate->method_id) {
$rates_arr[ $rate_id ] = $rate;
break;
}
}
}
return !empty( $rates_arr ) ? $rates_arr : $rates;
}
在添加代码片段之前,请确保您清除了WooCommerce缓存(WooCommerce> System Status> Tools> WC Transients> clear Transients),因为shipping方法被缓存了。
此代码位于您的活动子主题或主题的function.php文件上。
这段代码应该工作如果你正确地设置了你的运输区域…
引用:
- 当免费送货时隐藏其他送货方式
- WooCommerce -当免费送货时隐藏其他运输方法
- WooCommerce 2.6 -当达到特定金额触发免费送货时隐藏付费送货
- WooCommerce购物车-条件商品类别验证
- 如何在WooCommerce 2.6中设置航运区