Skip to content

Instantly share code, notes, and snippets.

@Acephalia
Created January 20, 2024 05:25
Show Gist options
  • Save Acephalia/8be8474b40f0bda5aad38f8cf5aab8b4 to your computer and use it in GitHub Desktop.
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
// 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;
}
@Acephalia
Copy link
Author

Acephalia commented Jan 20, 2024

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.

image

Solution for : https://www.reddit.com/r/woocommerce/s/bhBYXkIYRi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment