• Hey! I want to remove or add some shipping options depending on the category of product that is in cart. For example: I have one product from category X and I want to add shipping-method-X to cart. And if I have one product from category X and one from another category, then shipping-method-X is disabled.
    Function below checks if array contains category with ID=49 and if there is another category, but it doesn’t work. Nothing happens in cart ??

    add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_tag' ,    10, 1 );
    
    function check_cart_for_share() {
    
    global $woocommerce;
    $cart = $woocommerce->cart->cart_contents;
    
    $found = false;
    
    // loop through the array looking for the categories. Switch to true if the category is found.
      foreach ($woocommerce->cart->cart_contents as $key => $values ) {
            $terms = get_the_terms( $values['product_id'], 'product_cat' );
    
    		$tmp = array();
    
    		foreach ($terms as $term) {
    
    			array_push($tmp, $term->term_id); // wrzucenie ID kategorii do tablicy
    		}
    		array_unique($tmp);
    
            if (sizeof($tmp) > 1 AND in_array('49', $tmp)) {
    
            $found = true;
      }
    }
    
    return $found;
    
    }
    
    function hide_shipping_based_on_tag( $available_methods ) {
    
    // use the function above to check the cart for the categories.
    if ( check_cart_for_share() ) {
    
        // remove the method you want
        unset( $available_methods['flat_rate'] ); // Replace "local_pickup" with the shipping option that you want to remove.
    }
    
    // return the available methods without the one you unset.
    return $available_methods;
    
    }

    Whats wrong with this code?

    https://www.ads-software.com/plugins/woocommerce/

  • The topic ‘Filtering shipping method in cart’ is closed to new replies.