In WooCommerce cart page I am using the code below to check if specific shipping method is enabled, but the condition on the if statement is always true, so it doesn't work.
global $woocommerce;
$shipping_methods = $woocommerce->shipping->load_shipping_methods();
if ( $shipping_methods['free_shipping']->enabled == "yes" ) {
}
How can I Check on cart page if specific shipping method is enabled?
The method enabled()
will be yes if the "free_shipping" shipping method is enabled in WooCommerce shipping settings for the current shipping zone, that's why you always get "yes"…
To check that for WC_Cart
object, you will use instead WC_Session
related data. Here is an example for "Free shipping" shipping method:
// Get available shipping methods
$shipping_for_package_0 = WC()->session->get('shipping_for_package_0');
$found = false;
if( isset($shipping_for_package_0['rates']) && ! empty($shipping_for_package_0['rates']) ) {
// Loop through available shipping methods rate data
foreach( $shipping_for_package_0['rates'] as $rate ) {
// Targeting "Free Shipping"
if( 'free_shipping' === $rate->method_id ) {
$found = true;
break;
}
}
}
// Display availability for "Free shipping"
echo $found ? 'Free shipping is available.' : 'Free shipping is not available.';
But it will not get refreshed on cart page if the customer make changes on cart page.