'Make Shipping Method fields Mandatory on Woocommerce checkout page

I'm sure that there is a quick bit of code out there that will solve this issue, but I'm struggling to find it.

I have a WordPress/WooCommerce website set-up and am using the WooCommerce Shipping Pro with Table Rate plugin to specify delivery rates as well as the local pickup option, within WooCommerce's shipping settings.

This is all working fine, but have hit a slight issue.

On the checkout page - if neither shipping method is selected but all other fields are filled in, it still allows me to click on the Pay button and be taken to the Payment Gateway.

So, I am after a bit of code that will check to make sure a shipping method has been chosen or will make shipping method a mandatory field. So that when a customer clicks on Pay if no shipping method is selected it will not allow them to proceed and will flag up a warning.

Link to website: https://larchcottage.co.uk/



Solution 1:[1]

The following code will output an error message on checkout page, if no shipping method has been chosen when submitting the order:

// Validate shipping method fields and returning an error if none is choosed
add_action( 'woocommerce_checkout_process', 'shipping_method_validation', 20 );
function shipping_method_validation() {
    if ( ! isset( $_POST['shipping_method[0]'] ) ){
        wc_add_notice( __( "You need to choose your a shipping option.", "woocommerce" ), 'error' );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LoicTheAztec