php-使Woocommerce自定义结帐字段不可编辑

我在woocommerce结帐页面上添加了一个自定义字段,该字段由URL填充,但是我正在努力寻找一种使该字段不可编辑的方法.

我在function.php中添加了以下代码:

//Add custom field
function custom_woocommerce_checkout_fields( $checkout_fields = array() ) {

    $checkout_fields['order']['imei'] = array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('IMEI'),
        'placeholder'   => __('imei'),
        'default' => $_GET['imei'],            
    );

    return $checkout_fields;
}
add_filter( 'woocommerce_checkout_fields', 'custom_woocommerce_checkout_fields' );

要完成此操作,我应该在代码中进行哪些更改?

解决方法:

您应该尝试使用此文本< imput>具有readonly属性的字段(表示不可编辑).

You should need to have your ’emei’ set in the checkout url like:
http://www.example.com/checkout/?imei=3545454653 to make the field appear with the value as I have this condition: if( empty($_GET['imei'])) return;set in the function.

编码:

// Display
add_action( 'woocommerce_after_order_notes', 'custom_woocommerce_checkout_fields' );
function custom_woocommerce_checkout_fields( $checkout ) {
    // Only display field if the 'emei' is set in the checkout url
    if( empty($_GET['imei'])) return;

    echo '<p class="form-row my-field-class form-row-wide woocommerce-validated" id="imei_field">
        <label for="imei" class="">'.__('IMEI').'</label>
        <input type="text" class="input-text " name="imei" id="imei" placeholder="'.__('IMEI').'" value="'.$_GET['imei'].'" readonly>
    </p>';
}

// Save 
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta' );
function custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['imei'] ) ) {
        update_post_meta( $order_id, '_imei', sanitize_text_field( $_POST['imei'] ) );
    }
}

代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中.

经过测试并在WooCommerce版本3上工作

To get the value (for a defined $order_id):

06001

上一篇:php-如何在WooCommerce中为自定义产品类型启用价格和库存


下一篇:Woocommerce MySQL更新特定类别产品的价格