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

如何将WooCommerce自定义结账字段数据存入订单数据与用户元数据

我编写了如下代码,实现WooCommerce结账页允许用户填写额外用户数据的功能,该方案灵感来自Stack Overflow上的公开代码,目前无法找到原来源。

1. functions.php 自定义字段代码

该代码用于在WooCommerce结账页的订单备注区域前插入额外的会员信息填写区块:

add_action('woocommerce_before_order_notes','checkout_sections');
function checkout_sections(){
    echo '<div>';      
        echo '<h3>'. __( 'Add New Member', 'woocommerce' ).'</h3>';
        echo '<div class="row" id="readroot">';
        echo '<label for="fullname[]">Name and Surname</label>';
        echo '<div class="col-lg-2">';
        echo '<div class="md-form form-sm new_row">';
        echo '<input type="text" name="fullname[]" id="newfullname" placeholder="Name and Surname" class="form-control" required>';
        echo '</div>';
        echo '</div>';
        echo '<br>';
        echo '<label for="ALIMCode[]">A.L.IM. Membership Code</label>';
        echo '<div class="col-lg-2">';
        echo '<div class="md-form form-sm new_row">';
        echo '<input type="text" name="ALIMCode[]" id="newalimcode" placeholder="A.L.IM. Membership Code" class="form-control" required>';
        echo '</div>';
        echo '</div>';
        echo '<br>';
        echo '<div class="col-lg-2">';
        echo '<div class="md-form form-sm">';
        echo '<a id="moreFields" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Click to Add new A.L.IM. Member</a>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '<br>';
        echo '<div class="row" id="writeroot"></div>';
        echo '<div class="btn btn-sm btn-danger waves-effect waves-light pull-right" onclick="this.parentNode.parentNode;"><br>';
}
2. 字段克隆功能Javascript代码

该代码用于实现「添加新会员」按钮的点击逻辑,支持动态新增多组会员信息填写区块:

var counter = 0;

//document.getElementById('moreFields').onclick = moreFields;

window.onload = loadEventListener();

function loadEventListener() {
  let addRowAnchorTags = document.getElementsByClassName('moreFields');

  for(i=0;i<addRowAnchorTags.length; i++) {
      addRowAnchorTags[i].onclick = moreFields;
  }
}

function moreFields() {
  counter++;
  var newFields = document.getElementById('readroot').cloneNode(true);
  newFields.id = '';
  newFields.style.display = 'row';
  var newField = newFields.childNodes;
  for (var i = 0; i < newField.length; i++) {
    var theName = newField[i].name
    if (theName)
      newField[i].name = theName + counter;
  }
  var insertHere = document.getElementById('writeroot');
  insertHere.parentNode.insertBefore(newFields, insertHere);
  setTimeout(function() {loadEventListener();})
}
//window.onload = moreFields;
3. 实现效果

结账页前端展示效果如下:
结账页效果示意图

4. 需求说明

希望将上述动态新增的会员自定义字段数据,同步存储到WooCommerce订单数据以及对应用户的元数据中,预期在后台的展示效果如下:
预期效果示意图

5. 现有实现基础

目前已经实现了游客下单时自动创建用户账号,并将原有自定义字段同步存入用户元数据与订单数据的功能,对应代码如下:

// create account when buy
function action_woocommerce_thankyou( $order_id ) {
    // Determines whether the current visitor is a logged in user.
    if ( is_user_logged_in() ) return;
    
    // Get $order object
    $order = wc_get_order( $order_id );
    
    // Get the user email from the order
    $order_email = $order->billing_email;

    // Check if there are any users with the billing email as user or email
    $email = email_exists( $order_email );  
    $user = username_exists( $order_email );

    // If the UID is null, then it's a guest checkout (new user)
    if ( $user == false && $email == false ) {
        // Random password with 12 chars
        $random_password = wp_generate_password();
        
        // Firstname
        $first_name = $order->get_billing_first_name();
        
        // Lastname
        $last_name = $order->get_billing_last_name();

        // Role
        $role = 'customer';   //'customer'

        // Company Name
        $companys = $order->get_billing_company();

        // payment method (luca)
        $paymentuser = $order->get_payment_method_title();
        
        // Username (luca)
        $usernames = $first_name.$last_name.$companys; 
        
        // Create new user with email as username, newly created password and userrole          
        $user_id = wp_insert_user(
            array(
                'user_email' => $order_email,  //$order_mail
                'user_login' => $usernames,
                'user_pass'  => $random_password,
                'first_name' => $first_name,
                'last_name'  => $last_name,
                'role'       => $role,
            )
        );
        
        // Get all WooCommerce emails Objects from WC_Emails Object instance
        $emails = WC()->mailer()->get_emails();

        // Send WooCommerce "Customer New Account" email notification with the password
        $emails['WC_Email_Customer_New_Account']->trigger( $user_id, $random_password, true );

        // (Optional) WC guest customer identification
        //update_user_meta( $user_id, 'guest', 'yes' );

        //codice per recuperare url file upload

        //$codedocu = $order->review_order_before_submit_upload_distinta_di_pagamento;
        //$urldocu =  'https://alimdigital.org/?checkout_fields_get=';
        //$urldocufine = '&checkout_fields_nonce=318982cbce';
        //$codefinal = $urldocu.$codedocu.$urldocufine;


        //$codedocu2 = $order->review_order_before_submit_upload_documento_identita;
        //$codedocu3 = $order->review_order_before_submit_upload_selfie_con_documento_identita;
        //$codedocu4 = $order->review_order_before_submit_upload_visura_camerale;
        //$codedocu5 = $order->review_order_before_submit_upload_proposta_di_statuto;
        
        //$codefinales = $urldocu.$codedocu2.$urldocufine; 
        //$codeselfie = $urldocu.$codedocu3.$urldocufine;
        //$codevisura = $urldocu.$codedocu4.$urldocufine;
        //$codestatuto = $urldocu.$codedocu5.$urldocufine;

        // User's billing data
        update_user_meta( $user_id, 'billing_tipologia_iscritto', $order->billing_tipologia_iscritto );
        update_user_meta( $user_id, 'billing_nazione_sede_alim_di_riferimento', $order->billing_nazione_sede_alim_di_riferimento );
        update_user_meta( $user_id, 'billing_sede_alim_di_riferimento', $order->billing_sede_alim_di_riferimento );
        update_user_meta( $user_id, 'billing_categoria_socio', $order->billing_categoria_socio);
        update_user_meta( $user_id, 'billing_address_1', $order->billing_address_1 );
        update_user_meta( $user_id, 'billing_address_2', $order->billing_address_2);
        update_user_meta( $user_id, 'billing_city', $order->billing_city );
        update_user_meta( $user_id, 'billing_company', $order->billing_company );
        update_user_meta( $user_id, 'billing_codice_ateco_codice_nace', $order->billing_codice_ateco_codice_nace );
        update_user_meta( $user_id, 'billing_country', $order->billing_country );
        update_user_meta( $user_id, 'billing_email', $order->billing_email );
        update_user_meta( $user_id, 'billing_first_name', $order->billing_first_name );
        update_user_meta( $user_id, 'billing_last_name', $order->billing_last_name );
        update_user_meta( $user_id, 'billing_data_di_nascita', $order->billing_data_di_nascita );
        update_user_meta( $user_id, 'billing_phone', $order->billing_phone );
        update_user_meta( $user_id, 'billing_postcode', $order->billing_postcode );
        update_user_meta( $user_id, 'billing_state', $order->billing_state );
        update_user_meta( $user_id, 'billing_tipologia_territoriale_di_sede_alim_richiesta', $order->billing_tipologia_territoriale_di_sede_alim_richiesta );
        
        update_user_meta( $user_id, 'billing_nazione', $order->billing_nazione);
        update_user_meta( $user_id, 'billing_provincia', $order->billing_provincia);
        update_user_meta( $user_id, 'billing_citta', $order->billing_citta);
        update_user_meta( $user_id, 'billing_indirizzo', $order->billing_indirizzo);
        update_user_meta( $user_id, 'billing_cap', $order->billing_cap);

        update_user_meta( $user_id, 'billing_nazione_di_rilascio', $order->billing_nazione_di_rilascio);
        update_user_meta( $user_id, 'billing_ente_di_rilascio', $order->billing_ente_di_rilascio);
        update_user_meta( $user_id, 'billing_numero_documento', $order->billing_numero_documento);
        update_user_meta( $user_id, 'billing_data_rilascio_documento', $order->billing_data_rilascio_documento );
        update_user_meta( $user_id, 'billing_data_scadenza_documento', $order->billing_data_scadenza_documento );

        update_user_meta( $user_id, 'billing_nome_cognome_presidente', $order->billing_nome_cognome_presidente );
        update_user_meta( $user_id, 'billing_codice_iscrizione_alim', $order->billing_codice_iscrizione_alim );

        update_user_meta( $user_id, 'billing_nome_cognome_vicepresidente', $order->billing_nome_cognome_vicepresidente );
        update_user_meta( $user_id, 'billing_codice_iscrizione_alim2', $order->billing_codice_iscrizione_alim2 );

        update_user_meta( $user_id, 'billing_nome_cognome_segretario', $order->billing_nome_cognome_segretario );
        update_user_meta( $user_id, 'billing_codice_iscrizione_alim22', $order->billing_codice_iscrizione_alim22 );

        update_user_meta( $user_id, 'billing_nome_cognome_tesoriere', $order->billing_nome_cognome_tesoriere );
        update_user_meta( $user_id, 'billing_codice_iscrizione_alim222', $order->billing_codice_iscrizione_alim22 );

        update_user_meta( $user_id, 'billing_nome_cognome_consigliere', $order->billing_nome_cognome_consigliere );
        update_user_meta( $user_id, 'billing_codice_iscrizione_alim2222', $order->billing_codice_iscrizione_alim2222 );

        

        // Link past orders to this newly created customer
        wc_update_new_customer_past_orders( $user_id );
        
        // Auto login
        wp_set_current_user( $user_id );
        wp_set_auth_cookie( $user_id );
    }  
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 ); 

function filter_woocommerce_thankyou_order_received_text( $str, $order ) {
    // Determines whether the current visitor is a logged in user.
    if ( is_user_logged_in() ) return;
    
    // Get the user email from the order
    $order_email = $order->billing_email;
    
    // Check if there are any users with the billing email as user or email
    $email = email_exists( $order_email );  
    $user = username_exists( $order_email );

    // If the UID is null, then it's a guest checkout (new user)
    if ( $user == false && $email == false ) {
        // Link
        $link = get_permalink( get_option( 'woocommerce_myaccount_page_id' ) );

        // Format
        $format_link = '<a href="' . $link . '">logged in</a>';

        // Append to orginal string
        $str .= sprintf( __( ' An account has been automatically created for you and you are now %s. You will receive an email about this.', 'woocommerce' ), $format_link ); 
    }       

    return $str;
}
add_filter( 'woocommerce_thankyou_order_received_text', 'filter_woocommerce_thankyou_order_received_text', 10, 2 );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:54:07