简体   繁体   English

在woocommerce中添加一个带有随机唯一字符串值的结账隐藏字段

[英]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.在 Woocommerce 中,我想在结帐页面中添加一个隐藏字段,该属性值将是自定义生成的唯一随机字符串。

Is that possible?那可能吗?

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):你会得到类似这样生成的 html 代码(就在订单备注字段之前):

<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).所有代码都在活动子主题(或活动主题)的 function.php 文件中。 Tested and works.测试和工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM