John Davidson

php - Woocommerce, Checkout, Order -> Advanced Custom Field: set value from HTML selector

0 comments
Message:


How do I set the value of a custom field on an order, upon checkout submit, to a selected value in an HTML component?


I've implemented a custom HTML component, inside the checkout form, whose selected value I want to insert in a custom field on my orders. But I can't seem to figure out how to hook these things up.
I've arrived at somthing like:


add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
$fields['order']['special_delivery'] = 'The value from HTML';
return $fields;
}

But I'm not even sure that's the right way to go.


Any ideas?



My Answer:
You can achieve this by using jQuery to capture the selected value from your HTML component and then pass it to the custom field on the order upon checkout submit. Here's an example of how you can do this:

1. Add your custom HTML component to the checkout form. For example, you can add a select dropdown like this:

html



2. Add the following jQuery script to capture the selected value and pass it to the custom field on the order:

javascript
jQuery(document).ready(function($) {
$('form.checkout').on('submit', function() {
var specialDeliveryValue = $('#special_delivery').val();
$('input#special_delivery').val(specialDeliveryValue);
});
});


3. Add a hidden input field to store the selected value in the order:

php
add_action('woocommerce_checkout_update_order_meta', 'save_special_delivery_to_order_meta');

function save_special_delivery_to_order_meta( $order_id ) {
if ( ! empty( $_POST['special_delivery'] ) ) {
update_post_meta( $order_id, 'special_delivery', sanitize_text_field( $_POST['special_delivery'] ) );
}
}


With these steps, the selected value from your HTML component will be captured upon checkout submit and stored in the custom field 'special_delivery' on the order. You can then retrieve this value from the order meta data as needed.

Rate this post

3 of 5 based on 7406 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us