Woocommerce - custom functions runs only on update cart

183 views Asked by At

I wrote a very small function to disable installation as a method (from table rate shipping plugin) if a product is not in the cart or if the quantity of that product in the cart is less than 6.

This works, but only when I click on "update cart" button and not, for example, when I click on cart.

here's the function, directly from my function.php file in my custom theme:

function disable_installation_for_less_than( $rates ) {
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    $installation =  $rates['table_rate_shipping_installation'];

    foreach ( $items as $item => $values ) {
        $productID       = $values['product_id'];
        $productQuantity = $values['quantity'];
        unset( $rates['table_rate_shipping_installation'] );

        if ( $productID == 2412 ) {
            if ( $productQuantity < 6 ) {
                unset( $rates['table_rate_shipping_installation'] );
            } else {
                array_push($rates, $installation);
            }
        }
    }

    return $rates;
}

add_filter( 'woocommerce_package_rates', 'disable_installation_for_less_than', 10, 3 );

Any idea why? am I using the wrong hook? Thanks for any help

Also, rather then un-setting the installation and re-set it only when needed, is there a better way to say "if this product is NOT in the cart" then remove this?

thanks

1

There are 1 answers

0
Nick On BEST ANSWER

Ok, I managed to solve it this way:

function disable_installation_for_less_than( $rates ) {
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    $showInstallation= false;
    foreach ( $items as $item => $values ) {
        $productID       = $values['product_id'];
        $productQuantity = $values['quantity'];
        if ( $productID == 2412 ) {
            $showInstallation= true;
            if ( $productQuantity < 6 ) {
                unset( $rates['table_rate_shipping_installation'] );
            }
        }
    }

    if ($showInstallation== false){
        unset( $rates['table_rate_shipping_installation'] );
    }

    return $rates;
}

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

It's working now.