I'm currently using the code below to show a custom message based on country:
add_action( 'woocommerce_before_checkout_billing_form', 'display_shipping_notice' );
function display_shipping_notice() {
echo '<div class="shipping-notice woocommerce-info" style="display:none">Please allow 5-10 business days for delivery after order processing.</div>';
}
add_action( 'woocommerce_after_checkout_form', 'show_shipping_notice_js' );
function show_shipping_notice_js(){
?>
<script>
jQuery(document).ready(function($){
// Set the country code (That will display the message)
var countryCode = 'GB';
$('select#billing_country').change(function(){
selectedCountry = $('select#billing_country').val();
if( selectedCountry == countryCode ){
$('.shipping-notice').show();
}
else {
$('.shipping-notice').hide();
}
});
});
</script>
<?php
}
The problem with this code is that it will only show the message if the country is changed or selected. However, most customers already have their country pre-filled, so the custom message will not show.
I'm trying to find a way to alter the code to make the message always show when the correct country is selected.
I have revisited your code, changing:
But note that your jQuery code is handling Billing country (see at the end for shipping country).
Try the following instead:
add_action( 'woocommerce_checkout_before_customer_details', 'display_shipping_notice' );
function display_shipping_notice() {
echo '<div class="shipping-notice woocommerce-message" role="alert" style="display:none">Please allow 5-10 business days for delivery after order processing.</div>';
}
add_action( 'woocommerce_after_checkout_form', 'show_shipping_notice_js' );
function show_shipping_notice_js(){
?>
<script>
jQuery(function($){
var countryCode = 'GB', // Set the country code (That will display the message)
countryField = 'select#billing_country'; // The Field selector to target
function showHideShippingNotice( countryCode, countryField ){
if( $(countryField).val() === countryCode ){
$('.shipping-notice').show();
}
else {
$('.shipping-notice').hide();
}
}
// On Ready (after DOM is loaded)
showHideShippingNotice( countryCode, countryField );
// On billing country change (Live event)
$('form.checkout').on('change', countryField, function() {
showHideShippingNotice( countryCode, countryField );
});
});
</script>
<?php
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Caution: If you want to handle the shipping country instead of billing country, replace:
countryField = 'select#billing_country'; // The Field selector to target
with this:
countryField = 'select#shipping_country'; // The Field selector to target
Now It will handle Shipping country.