Created
January 20, 2024 05:25
-
-
Save Acephalia/8be8474b40f0bda5aad38f8cf5aab8b4 to your computer and use it in GitHub Desktop.
Woocommerce Disable/Enable Shipping Methods based on the number of products in the cart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Disable/Enable Shipping Methods based on the number of products in the cart by u/acephaliax | |
add_filter( 'woocommerce_package_rates', 'conditionally_enable_shipping_methods', 10, 2 ); | |
function conditionally_enable_shipping_methods( $rates, $package ) { | |
$cart_items_count = WC()->cart->get_cart_contents_count(); | |
// Instance IDs to adjust (replace with your actual IDs) | |
$method_id_to_disable_for_large_carts = 9; | |
$method_id_to_enable_for_large_carts = 10; | |
//Set cart item quantity to trigger rule | |
if ( $cart_items_count > 2 ) { | |
// Disable method 9 and enable method 10 | |
foreach ( $rates as $rate_key => $rate ) { | |
if ( $rate->get_instance_id() == $method_id_to_disable_for_large_carts ) { | |
unset( $rates[$rate_key] ); | |
} elseif ( $rate->get_instance_id() == $method_id_to_enable_for_large_carts ) { | |
$rate->enabled = true; | |
} | |
} | |
} else { | |
// Disable method 10 and enable method 9 | |
foreach ( $rates as $rate_key => $rate ) { | |
if ( $rate->get_instance_id() == $method_id_to_disable_for_large_carts ) { | |
$rate->enabled = true; | |
} elseif ( $rate->get_instance_id() == $method_id_to_enable_for_large_carts ) { | |
unset( $rates[$rate_key] ); | |
} | |
} | |
} | |
return $rates; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To find shipping instance ID go into the shipping zone and hower over the shipping method edit link, give it a sec and the full url should pop up on your broswer. Alternatively just click through and it will be i thr url.
Solution for : https://www.reddit.com/r/woocommerce/s/bhBYXkIYRi