1

I am trying to make the order/shipping notes field mandatory on the checkout page, for a specific shipping method.

Following this thread: Make Order notes required if shipping method is local pickup in Woocommerce, I am using below code:

add_action( 'woocommerce_checkout_process', 'danskefragtmand_order_comment_validation', 20 );
function danskefragtmand_order_comment_validation() {
    $chosen_shipping = WC()->session->get( 'chosen_shipping_methods' )[0];
    $chosen_shipping = explode(':', $chosen_shipping);
  
    if ( $chosen_shipping[0] == 'shipmondo:26' && empty($_POST['order_comments']) ){
        wc_add_notice( __( "Please tell the courier where he can leave your package in case you are not at home during time of delivery.", "woocommerce" ), 'error' );
    }
}

The code above works very well if I use the standard woocommerce shipping terms such as local_pickup and free_shipping, and also if u change my own term shipmondo:26 to just shipmondo, but then the notice will display for all other shipmondo shipping methods. I am trying to target the specific ID 26.

Any advice would be appriciated.

Other helpful thread: Disable only specific flat rate shipping method when free shipping is available in WooCommerce

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Richard
  • 61
  • 7

1 Answers1

2

You need, in the code, to replace the line:

if ( $chosen_shipping[0] == 'shipmondo:26' && empty($_POST['order_comments']) ){

with:

if ( $chosen_shipping === 'shipmondo:26' && empty($_POST['order_comments']) ){

Now it should work.

To make the code even better, replace your code with:

add_action( 'woocommerce_checkout_process', 'danskefragtmand_order_comment_validation', 20 );
function danskefragtmand_order_comment_validation() {
    $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');

    if ( in_array('shipmondo:26', $chosen_shipping_methods) && empty($_POST['order_comments']) ){
        wc_add_notice( __( "Please tell the courier where he can leave your package in case you are not at home during time of delivery.", "woocommerce" ), 'error' );
    }
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • 1
    Hi @LoicTheAztec, thank you for the the prompt reply and solution! It is working now as expected, and I now know what I did wrong. Please also accept my kind donation (paypal) on behalf of the company I work for. Wishing you a good day :) – Richard Jun 28 '23 at 10:18