Search code examples
phpwordpresswoocommercehook-woocommerceshipping-method

How to disable shipping method based on item count and a certain category


I have been looking for a way to condtionally disable two shipping methods

  • table rate
  • distance rate

Based on the item count.

By item count I do not mean quantity, I mean how many different products are in the cart. IE 2 Lamps and 3 tables in the cart would be an item count of 2 and a combined quantity of 5.

I would also like to ensure this rule is in effect for a certain category only.

I tried:

function hide_shipping_count_based( $rates, $package ) {

    // Set count variable
    $cart_count = 0;

    // Calculate cart's total
    foreach( WC()->cart->cart_contents as $key => $value) {
        $cart_count ++;
    }

    // only if the weight is over 150lbs find / remove specific carrier
    if( $cart_count > 2 ) {
        // loop through all of the available rates

        unset( $rates[ 'distance_rate' ] );
        unset( $rates[ 'table_rate' ] );

    }

    return $rates;
}

add_filter( 'woocommerce_package_rates', 'hide_shipping_count_based', 10, 2 );

Solution

  • You could use the following, explanation with comments added in the code

    Conditions that must be met in this code are:

    • At least 3 line items in cart
    • 1 or more products belong to the 'categorie-1' category
    • 'distance_rate' and/or 'table_rate' become unset if the previous 2 conditions are met

    function hide_shipping_count_based( $rates, $package ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        // Count line items
        $count =  count( $package['contents'] );
    
        // Set variable
        $found = false;
    
        // Set term (category)
        $term = 'categorie-1';
    
        // Check count
        if( $count > 2 ) {
    
            // Loop through line items
            foreach( $package['contents'] as $line_item ) {
                // Get product id
                $product_id = $line_item['product_id'];
    
                // Check for category
                if ( has_term( $term, 'product_cat', $product_id ) ) {
                    $found = true;
                    break;
                }
            }
        }
    
        // True
        if ( $found ) {
            // Loop trough rates
            foreach ( $rates as $rate_key => $rate ) {
                // Targeting
                if ( in_array( $rate->method_id, array( 'distance_rate', 'table_rate' ) ) ) {
                    unset( $rates[$rate_key] );
                }
            }
        }
    
        return $rates;
    }
    add_filter( 'woocommerce_package_rates', 'hide_shipping_count_based', 100, 2 );