During checkout I want to know if the buyer is a company or an individual. If the buyer is a company, I need to show them required company name and code fields. But if they check that they are an individual, those fields should not be required.
I tried using woocommerce_after_checkout_validation hook to check if the required radio button is checked and unset the above mentioned fields. But this doesn't work.
These are my fields that I have created:
//Custom checkout fields for companies
function imones_kodas_add_checkout_fields( $fields ) {
$fields[ 'billing_imones_kodas' ] = array(
'label' => __( 'Įmonės kodas' ),
'type' => 'text',
'class' => array( 'form-row-wide' ),
'priority' => 35,
'required' => true,
);
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'imones_kodas_add_checkout_fields' );
function pvm_add_checkout_fields( $fields ) {
$fields[ 'billing_pvm_kodas' ] = array(
'label' => __( 'PVM kodas' ),
'description' => 'Jei esate PVM mokėtojas, būtinai nurodykite įmonės PVM mokėtojo kodą',
'type' => 'text',
'class' => array( 'form-row-wide' ),
'priority' => 36,
'required' => false,
);
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'pvm_add_checkout_fields' );
function imone_privatus_checkout_radio( $fields ) {
$fields[ 'billing_radio' ] = array(
'label' => __( 'Pasirinkite kas perka' ),
'type' => 'radio',
'class' => array( 'form-row-wide' ),
'priority' => 5,
'required' => true,
'options' => array(
'privatus_asmuo' => 'Privatus asmuo',
'imone' => 'Įmonė',
),
);
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'imone_privatus_checkout_radio' );
This is my attempt to check what radio button is checked and then unset the fields.
add_action( 'woocommerce_after_checkout_validation', 'misha_validate_fname_lname', 100, 2);
function misha_validate_fname_lname( $fields, $errors ){
if($fields[ 'billing_radio' ] == 'privatus_asmuo'){
unset( $fields[ 'billing' ][ 'billing_pvm_kodas' ] );
unset( $fields[ 'billing' ][ 'billing_imones_kodas' ] );
unset( $fields[ 'billing' ][ 'billing_company' ] );
$fields[ 'billing' ][ 'billing_pvm_kodas' ]['required'] = false;
$fields[ 'billing' ][ 'billing_imones_kodas' ]['required'] = false;
$fields[ 'billing' ][ 'billing_company' ]['required'] = false;
return $fields;
}
}
In the end, if the the radio button is checked to 'privatus_asmuo', then the company related fields should not be validated. Is there a way to solve this problem using PHP? Or do I need to use JS and if so, how should I do it?