Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Woocommerce Checkout: Custom fields, conditional based on Gateway WordPress

  • SOLVED

I have added a custom woocommerce checkout field that I need to be 'required' ONLY for the 'cheque' gateway. Meaning, that selecting the "cheque" gateway, or selecting another, determines whether the custom field is required.
Here's the code currently in my functions.php that currently just adds the field, and makes sure it has content entered:


add_action( 'woocommerce_after_checkout_billing_form', 'c_custom_checkout_field' );
function c_custom_checkout_field( $checkout ) {

echo '<div id="c_custom_checkout_field"><h3>' . __('Custom Information') . '</h3>';

woocommerce_form_field( 'c_type', array(
'type' => 'text',
'class' => array('my-field-class form-row form-row-wide'),
'label' => __('Custom Info'),
'placeholder' => __('Custom Info'),
), $checkout->get_value( 'c_type' ));
echo '</div>';
}

add_action('woocommerce_checkout_process', 'c_custom_checkout_field_process');
function c_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['c_type'] )
wc_add_notice( __( 'Please enter the custom field.' ), 'error' );

}


Note that the 2nd function "c_custom_checkout_field_process" makes the field required in general. I would like to make this conditional so it is only required when the payment gateway is set to 'cheque'.

Thanks.

Answers (2)

2015-04-28

Reigel Gallarde answers:

try this...

add_action('woocommerce_checkout_process', 'c_custom_checkout_field_process');

function c_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['c_type'] && ($_POST['payment_method'] == 'cheque'))
wc_add_notice( __( 'Please enter the custom field.' ), 'error' );

}


bgnh comments:

Thanks. That worked

2015-04-28

Romel Apuya answers:

add_action('woocommerce_checkout_process', 'c_custom_checkout_field_process');
function c_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['c_type'] && isset($available_gateways['cheque']))
wc_add_notice( __( 'Please enter the custom field.' ), 'error' );

}