I'm having a problem with saving custom checkbox value in woocommerce cart and checkout.
I've added custom checkbox to checkout shipping table that adds custom bag if certain shipping method is selected. If checkbox is checked and I choose other shipping method and then return to a certain one with checkbox, checkbox is unchecked on ajax reload of cart summary.
I tried to save checkbox value in cookies with something like this
var checkbox = $('#your-form :checkbox:first'),
checkboxCookieName = 'checkbox-state';
checkbox.prop('checked', +$.cookie(checkboxCookieName));
checkbox.click(function() {
$.cookie(checkboxCookieName, +this.checked);
});
But it didn't work.
Code for checkbox:
function my_custom_checkout_field() {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ($chosen_shipping == 'nova_poshta_shipping_method') {
echo '<div id="my_custom_checkout_field">';
woocommerce_form_field( 'my_field_name', array(
'type' => 'checkbox',
'checked' => 'checked',
'class' => array('input-checkbox'),
'label' => __('<span class="paperbagspan">Добавить фирменный пакет <img class="paperbag" src="https://paradisefruit.com.ua/wp-content/uploads/2019/06/paper-bag.png" style="width:30px"><img class="paperbagpink" style="display:none; width:30px" src="https://paradisefruit.com.ua/wp-content/uploads/2019/06/paper-bag-pink.png" ></span>'),
), WC()->checkout->get_value( 'my_field_name' ) );
echo '</div>';
}
}
add_action( 'woocommerce_after_shipping_rate', 'checkout_shipping_additional_field', 20, 2 );
function checkout_shipping_additional_field( $method, $index )
{
if( $method->get_id() == 'nova_poshta_shipping_method' ){
return my_custom_checkout_field();
}
}
// Save the custom checkout field in the order meta, when checkbox has been checked
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta', 10, 1 );
function custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['my_field_name'] ) )
update_post_meta( $order_id, 'my_field_name', sanitize_text_field($_POST['my_field_name'] ));
}
What am I doing wrong or is there some wordpress fuction that saves custom field values?