mirror of
https://gh.wpcy.net/https://github.com/mainwp/Code-Snippets-Functions.git
synced 2026-05-03 12:12:25 +08:00
https://stackoverflow.com/questions/77095984/hide-a-shipping-method-when-a-subscription-is-in-cart-in-woocommerce/77097208
21 lines
802 B
Text
21 lines
802 B
Text
// Conditional function: Check if cart has a subscription
|
|
function has_subscription_product( $cart_contents ) {
|
|
foreach ( $cart_contents as $item ) {
|
|
if ( $item['data']->is_type( array('subscription', 'subscription_variation') ) ) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// Hide shipping method conditionally
|
|
add_filter( 'woocommerce_package_rates', 'filter_package_shipping_rates', 10, 2 );
|
|
function filter_package_shipping_rates( $rates, $package ) {
|
|
$targeted_id = 'chrono13'; // Here define the targeted shipping method rate ID
|
|
|
|
// If there is a subscription in cart
|
|
if( has_subscription_product( WC()->cart->get_cart() ) && isset($rates[$targeted_id]) ) {
|
|
unset($rates[$targeted_id]); // Hide the shipping method
|
|
}
|
|
return $rates;
|
|
}
|