admin管理员组

文章数量:1302401

I am looking forward on how to hide shipping at all from the checkout page of Woocommerce when only certain product (magazine) is in the cart or much better would be, if the only product/s with certain shipping class are in the cart.

If there is a combination of products (magazine + books), then shipping module should be visible.

This is what I have tried, but this always returns false. Can you help me out on this?

add_filter( 'woocommerce_package_rates', 'woocommerce_cart_shipping_total_filter_callback', 11, 2 );
function woocommerce_cart_shipping_total_filter_callback( $show_abon_shipping) {
    
    $product_id = 27733;
   $in_cart = false;
  
   foreach( WC()->cart->get_cart() as $cart_item ) {
      $product_in_cart = $cart_item['product_id'];
        if ( $product_in_cart === $product_id && count($product_in_cart) == 1) {
            $in_cart = true;
    }
   }
  
   if ( $in_cart ) {
  
     return false;
  
   }

     return $show_abon_shipping;
}

I am looking forward on how to hide shipping at all from the checkout page of Woocommerce when only certain product (magazine) is in the cart or much better would be, if the only product/s with certain shipping class are in the cart.

If there is a combination of products (magazine + books), then shipping module should be visible.

This is what I have tried, but this always returns false. Can you help me out on this?

add_filter( 'woocommerce_package_rates', 'woocommerce_cart_shipping_total_filter_callback', 11, 2 );
function woocommerce_cart_shipping_total_filter_callback( $show_abon_shipping) {
    
    $product_id = 27733;
   $in_cart = false;
  
   foreach( WC()->cart->get_cart() as $cart_item ) {
      $product_in_cart = $cart_item['product_id'];
        if ( $product_in_cart === $product_id && count($product_in_cart) == 1) {
            $in_cart = true;
    }
   }
  
   if ( $in_cart ) {
  
     return false;
  
   }

     return $show_abon_shipping;
}
Share Improve this question asked Mar 12, 2021 at 7:35 jamjam 1732 gold badges3 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Solved it. Just remeber to add the same shipping class to all variations too.

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

    $shipping_class = 506; // HERE set the shipping class ID
    $found = false;
    $productsincart = count($package['contents']);
    
    foreach( $package['contents'] as $cart_item ) {
            
        if ($productsincart == 1 && $cart_item['data'];->get_shipping_class_id() == $shipping_class){
            $found = true;
        }   
    }

    if ( $found ) {
        return false; // If not found we exit
    }else {
        return $rates;
        
    }
}

本文标签: