58
If you have country-specific shipping conditions, or you want to show a message conditionally after country selection on the checkout page, here’s a simple WooCommerce PHP snippet you can freely use. This can be slightly customized to target state selection instead.
I’ve also edited the initial code to make this work on load as well, so that the message would conditionally show even then. Enjoy!
PHP Snippet: Display Conditional Content @ WooCommerce Checkout
/**
* @snippet Show Conditional Message Upon Country Selection @ WooCommerce Checkout
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 5
* @donate $9 https://tutoraspire.com
*/
// Part 1
// Add the message notification and place it over the billing section
// The "display:none" hides it by default
add_action( 'woocommerce_before_checkout_billing_form', 'tutoraspire_echo_notice_shipping' );
function tutoraspire_echo_notice_shipping() {
echo '
';
}
// Part 2
// Show or hide message based on billing country
add_action( 'woocommerce_after_checkout_form', 'tutoraspire_show_notice_shipping' );
function tutoraspire_show_notice_shipping(){
wc_enqueue_js( "
// Set the country code that will display the message
var countryCode = 'FR';
// Get country code from checkout
selectedCountry = $('select#billing_country').val();
// Function to toggle message
function toggle_upsell( selectedCountry ) {
if( selectedCountry == countryCode ){
$('.shipping-notice').show();
}
else {
$('.shipping-notice').hide();
}
}
// Call function
toggle_upsell( selectedCountry );
$('select#billing_country').change(function(){
toggle_upsell( this.value );
});
" );
}