diff --git a/includes/class-wc-cart.php b/includes/class-wc-cart.php index 23bf0737653..159660a1c26 100644 --- a/includes/class-wc-cart.php +++ b/includes/class-wc-cart.php @@ -1528,7 +1528,15 @@ class WC_Cart extends WC_Legacy_Cart { } if ( 'yes' === get_option( 'woocommerce_shipping_cost_requires_address' ) ) { - if ( ! $this->get_customer()->get_shipping_country() || ! $this->get_customer()->get_shipping_state() || ! $this->get_customer()->get_shipping_postcode() ) { + $country = $this->get_customer()->get_shipping_country(); + if ( ! $country ) { + return false; + } + $country_fields = WC()->countries->get_address_fields( $country, 'shipping_' ); + if ( isset( $country_fields['shipping_state'] ) && $country_fields['shipping_state']['required'] && ! $this->get_customer()->get_shipping_state() ) { + return false; + } + if ( isset( $country_fields['shipping_postcode'] ) && $country_fields['shipping_postcode']['required'] && ! $this->get_customer()->get_shipping_postcode() ) { return false; } } diff --git a/tests/php/includes/class-wc-cart-test.php b/tests/php/includes/class-wc-cart-test.php index 093cbf2a4cb..c4b31632c03 100644 --- a/tests/php/includes/class-wc-cart-test.php +++ b/tests/php/includes/class-wc-cart-test.php @@ -99,4 +99,37 @@ class WC_Cart_Test extends \WC_Unit_Test_Case { WC()->cart->get_customer()->set_shipping_state( '' ); WC()->cart->get_customer()->set_shipping_postcode( '' ); } + + /** + * Test show_shipping for countries with various state/postcode requirement. + */ + public function test_show_shipping_for_countries_different_shipping_requirements() { + $default_shipping_cost_requires_address = get_option( 'woocommerce_shipping_cost_requires_address', 'no' ); + update_option( 'woocommerce_shipping_cost_requires_address', 'yes' ); + + WC()->cart->empty_cart(); + $this->assertFalse( WC()->cart->show_shipping() ); + + $product = WC_Helper_Product::create_simple_product(); + WC()->cart->add_to_cart( $product->get_id(), 1 ); + + // Country that does not require state. + WC()->cart->get_customer()->set_shipping_country( 'LB' ); + WC()->cart->get_customer()->set_shipping_state( '' ); + WC()->cart->get_customer()->set_shipping_postcode( '12345' ); + $this->assertTrue( WC()->cart->show_shipping() ); + + // Country that does not require postcode. + WC()->cart->get_customer()->set_shipping_country( 'NG' ); + WC()->cart->get_customer()->set_shipping_state( 'AB' ); + WC()->cart->get_customer()->set_shipping_postcode( '' ); + $this->assertTrue( WC()->cart->show_shipping() ); + + // Reset. + update_option( 'woocommerce_shipping_cost_requires_address', $default_shipping_cost_requires_address ); + $product->delete( true ); + WC()->cart->get_customer()->set_shipping_country( 'GB' ); + WC()->cart->get_customer()->set_shipping_state( '' ); + WC()->cart->get_customer()->set_shipping_postcode( '' ); + } }