You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在WooCommerce中添加复选框控制结账字段显隐并在后台展示值

问题根因

你的代码缺少结账提交时保存自定义字段到订单元数据的逻辑,仅实现了前端字段展示和后台读取字段的功能,没有完成中间的存储步骤,所以后台读取到的字段值为空。

解决方法

在现有代码基础上新增以下代码即可:

/**
 * 保存自定义结账字段到订单元数据
 */
add_action( 'woocommerce_checkout_update_order_meta', 'save_custom_checkout_fields_to_order' );
function save_custom_checkout_fields_to_order( $order_id ) {
    // 保存复选框状态
    if ( ! empty( $_POST['checkbox_trigger'] ) ) {
        update_post_meta( $order_id, '_checkbox_trigger', sanitize_text_field( $_POST['checkbox_trigger'] ) );
    }
    // 保存企业名称
    if ( ! empty( $_POST['new_billing_field'] ) ) {
        update_post_meta( $order_id, '_new_billing_field', sanitize_text_field( $_POST['new_billing_field'] ) );
    }
    // 保存企业注册码
    if ( ! empty( $_POST['new_billing_field2'] ) ) {
        update_post_meta( $order_id, '_new_billing_field2', sanitize_text_field( $_POST['new_billing_field2'] ) );
    }
    // 保存企业地址
    if ( ! empty( $_POST['new_billing_field3'] ) ) {
        update_post_meta( $order_id, '_new_billing_field3', sanitize_text_field( $_POST['new_billing_field3'] ) );
    }
}

可选优化(高版本WooCommerce兼容)

如果使用WooCommerce 3.0+版本,建议将后台显示字段的代码替换为兼容性更好的原生方法:

add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('Ostan ettevõttena').':</strong> ' . $order->get_meta( '_new_billing_field', true ) . '</p>';
    echo '<p><strong>'.__('Ettevõtte aadress').':</strong> ' . $order->get_meta( '_new_billing_field3', true ) . '</p>';
    echo '<p><strong>'.__('Ettevõtte registrikood').':</strong> ' . $order->get_meta( '_new_billing_field2', true ) . '</p>';
}

添加代码后重新提交测试订单,后台就能正常显示字段值了。

内容的提问来源于stack exchange,提问作者Shaggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:24:00