Ask Your Question
4

How can custom field data in WooCommerce be saved as order meta key?

asked 2022-03-22 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-08-29 09:00:00 +0000

pufferfish gravatar image

You can save custom field data in WooCommerce as order meta key by using the following code:

  1. First, you need to add a custom field to the cart/checkout page in WooCommerce. You can do this by adding the following code to your functions.php file:
add_action( 'woocommerce_after_order_notes', 'add_custom_checkout_field' );

function add_custom_checkout_field( $checkout ) {

    echo '<div id="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>';

    woocommerce_form_field( 'my_field_name', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Enter Something'),
        'placeholder'   => __('Enter Something'),
        'required'      => false,
    ), $checkout->get_value( 'my_field_name' ));

    echo '</div>';

}

This will add a custom field named "myfieldname" to the checkout page.

  1. Next, you need to save the value of this custom field as an order meta key. You can do this by adding the following code to your functions.php file:
add_action( 'woocommerce_checkout_update_order_meta', 'save_my_field_name' );

function save_my_field_name( $order_id ) {

    if ( ! empty( $_POST['my_field_name'] ) ) {
        update_post_meta( $order_id, 'My Field Name', sanitize_text_field( $_POST['my_field_name'] ) );
    }
}

This code will save the value of the "myfieldname" custom field as an order meta key named "My Field Name". You can replace "My Field Name" with whatever meta key name you'd like to use.

That's it! Now, the custom field data will be saved as an order meta key in WooCommerce.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-22 11:00:00 +0000

Seen: 11 times

Last updated: Aug 29 '22