Search code examples
phpwordpresswoocommerceshipping-methodproduct-quantity

WooCommerce remove shipping method based on product IDs & quantity bought


I am trying to remove a shipping method based on two parameters in my cart. Parameter 1 = Product ID Parameter 2 = Quantity added for that Product ID.

I have been searching around and combining different solutions, however using the snippet underneath still doesn't give me the correct result. The expected result would be that if any of the products ( 6 , 9, 69 , 71 ) are added 52 times to my cart, the shipping fee (flexible_shipping_2_1) should dissapear.

All suggestions would be appreciated.

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {

    $product_ids = array( 6 , 9, 69 , 71 ); // HERE set the product IDs in the array
    $method_id = 'flexible_shipping_2_1'; // HERE set the shipping method ID
    $found = false;
    

    // Loop through cart items Checking for defined product IDs
    foreach( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
        if ( in_array( $cart_item['product_id'], $product_ids ) && $cart_item['quantity'] == 52){
            $found = true;
            break;
        }
    }
    if ( $found )
        unset( $rates[$method_id] );

    return $rates;
}

Solution

  • Maybe this is what you would like (to get the cumulated quantity for all defined product ids):

    add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
    function specific_products_shipping_methods( $rates, $package ) {
    
        $product_ids = array( 6 , 9, 69 , 71 ); // HERE set the product IDs in the array
        $method_id   = 'flexible_shipping_2_1'; // HERE set the shipping method ID
        $quantity    = 0;
        
    
        // Get cart items for the current shipping package
        foreach( $package['contents'] as $cart_item ) {
            if ( in_array( $cart_item['product_id'], $product_ids ) ){
                $quantity += $cart_item['quantity'];
            }
        }
        
        if ( $quantity >= 52 && isset($rates[$method_id]) ) {
            unset($rates[$method_id]);
        }
            
    
        return $rates;
    }
    

    Don't forget to empty your cart, to refresh shipping cached data…