user1915410
user1915410

Reputation: 81

Add a checkout hidden field with a random unique string value in woocommerce

In Woocommerce, I would like to add a hidden field to in checkout page, which attribute value will be a custom generated unique random string of character.

Is that possible?

Upvotes: 1

Views: 1278

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253968

This is very easy to do it… try the following:

add_action( 'woocommerce_before_order_notes', 'additional_hidden_checkout_field' );
function additional_hidden_checkout_field() {
    // echo '<input type="hidden" name="custom_unique_key" value="'.md5( microtime() . rand() ).'">';
    echo '<input type="hidden" name="yudu_pw" value="'.rand(102548, 984675).'">';
}

You will get something like this generated html code (just before order notes field):

<div class="woocommerce-additional-fields">
    <input type="hidden" name="yudu_pw" value="837542">

Then you could be able to save that custom random string of characters value using:

add_action( 'woocommerce_checkout_create_order', 'additional_hidden_checkout_field_save', 20, 2 );
function additional_hidden_checkout_field_save( $order, $data ) {
    if( ! isset($_POST['yudu_pw']) ) return;

    if( ! empty($_POST['yudu_pw']) ){
        $order->update_meta_data( 'yudu_pw', sanitize_text_field( $_POST['yudu_pw'] ) );
    }
}

So this custom random string of characters value will be saved as order meta data…

All code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 1

Related Questions