Add a custom checkbox in WooCommerce checkout which value shows in admin edit order

15,533

You can do it in 3 steps:

  1. Adding the custom checkbox field below the Payment Methods
  2. Saving the custom checkbox field when it's checked in the order meta
  3. Displaying the custom checkbox field when it's checked on the order edit page

Here is that code:

// 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>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested in WooCommerce 3+ and works. When the checkbox has been checked, it display a custom text below billing address in order edit page…

Share:
15,533
sHamann
Author by

sHamann

I like providing simple solutions to perplexing puzzles to people, which lead me to my profession with developing software. The fast growing world of technologies confront us with a lot of problems each day, therefore we have to adapt and keep learning every day to find the most viable solution to help ourself and the team around us.

Updated on July 05, 2022

Comments

  • sHamann
    sHamann almost 2 years

    I try to add an <input type="checkbox"> which value also shows at the woocommerce backend, so I can see at the end if the costumer ticked the box or not.

    The checkbox should be below the Payment Methods.

    Is it possible to add a custom checkbox in WooCommerce checkout which value shows in admin edit order?