Reputation: 337
I've got problem with validating checkbox in WooCommerce custom checkout field. I've seen this but it doesn't really help me. Custom field is generated inside form, so It should work good. I don't know if there is a need to put something more than my code in this particular case... I've tried few more hooks, but It doesn't made any effect.
add_action('woocommerce_review_order_before_submit', 'my_required_checkout_field');
function my_required_checkout_field( ) {
woocommerce_form_field( 'przetwarzanie_danych_do_zamowienia', array(
'type' => 'checkbox',
'class' => array('input-checkbox'),
'label' => __('REQUIRED ONE.'),
'required' => true,
), WC()->checkout->get_value( 'przetwarzanie_danych_do_zamowienia' ));
}
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
global $woocommerce;
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['przetwarzanie_danych_do_zamowienia']) update_post_meta( $order_id, 'Oświadczenie o zapoznaniu się z regulaminem', esc_attr($_POST['przetwarzanie_danych_do_zamowienia']));
}
Upvotes: 1
Views: 1824
Reputation: 3562
you are not adding the condition when your check box is not checked you have empty function my_custom_checkout_field_process
so here is full working code:
add_action('woocommerce_review_order_before_submit', 'my_required_checkout_field');
function my_required_checkout_field()
{
woocommerce_form_field('przetwarzanie_danych_do_zamowienia', array(
'type' => 'checkbox',
'class' => array('input-checkbox'),
'label' => __('REQUIRED ONE.'),
'required' => true,
), WC()->checkout->get_value('przetwarzanie_danych_do_zamowienia'));
}
/**
* Process the checkout
**/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process()
{
// Check if set, if its not set add an error.
if (!$_POST['przetwarzanie_danych_do_zamowienia']) {
wc_add_notice(__('Please select required box'), 'error');
}
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta($order_id)
{
if ($_POST['przetwarzanie_danych_do_zamowienia']) {
update_post_meta($order_id, 'Oświadczenie o zapoznaniu się z regulaminem', esc_attr($_POST['przetwarzanie_danych_do_zamowienia']));
}
}
Upvotes: 2