Created
June 4, 2020 15:11
-
-
Save zigojacko/4833f6017721e0f4fc1b840c7f92b420 to your computer and use it in GitHub Desktop.
Add custom checkbox to WooCommerce checkout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Source: https://stackoverflow.com/a/45911284/898933 | |
// Add custom checkout field: woocommerce_review_order_before_submit | |
add_action( 'woocommerce_review_order_before_submit', 'my_custom_checkout_field' ); | |
function my_custom_checkout_field() { | |
echo '<div id="my_custom_checkout_field">'; | |
woocommerce_form_field( 'my_field_name', array( | |
'type' => 'checkbox', | |
'class' => array('input-checkbox'), | |
'label' => __('My custom checkbox'), | |
), WC()->checkout->get_value( 'my_field_name' ) ); | |
echo '</div>'; | |
} | |
// 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', $_POST['my_field_name'] ); | |
} | |
// Display the custom field result on the order edit page (backend) when checkbox has been checked | |
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_custom_field_on_order_edit_pages', 10, 1 ); | |
function display_custom_field_on_order_edit_pages( $order ){ | |
$my_field_name = get_post_meta( $order->get_id(), 'my_field_name', true ); | |
if( $my_field_name == 1 ) | |
echo '<p><strong>My custom field: </strong> <span style="color:red;">Is enabled</span></p>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment