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

WooCommerce中为订单关联已分配唯一客户编码问题求助

WooCommerce客户编码与订单关联及展示问题处理记录

问题背景

我正在开发电商项目,客户下单时会被分配基于姓名和序号生成的客户编码,供财务软件使用。借助StackOverflow修正并添加了生成访客用户及自定义编码的代码,但编码未与订单关联,例如订单WC0001979无法查看对应客户编码。

尝试以下代码关联编码与订单,同时在WooCommerce订单页面添加编码展示标签“IPX Customer Code”,但标签能显示,实际编码无法展示:

add_action( 'woocommerce_checkout_update_order_meta', 'include_customer_code_on_order', 10, 2 );

function include_customer_code_on_order( $order_id, $posted_data ) {
    $order = wc_get_order( $order_id );
    $user_id = $order->get_user_id();

    if ( $user_id ) {
        $customer_code = get_user_meta( $user_id, 'ipx_customer_code', true );
        if ( $customer_code ) {
            $order->update_meta_data( 'ipx_customer_code', $customer_code );
            $order->save();
        }
    }
}

更新:适配全用户角色的关联代码

发现原代码仅支持访客用户,修改后实现所有用户角色的客户编码与订单关联:

add_action( 'woocommerce_order_status_changed', 'link_ipx_customer_code_to_the_order', 10, 4 );
function link_guest_ipx_customer_code_to_the_order( $order_id, $status_from, $status_to, $order  ) {
    // Check that no "IPX Customer Code is assigned
    if ( ! $order->get_meta('ipx_customer_code') ) {
        // Get the WP_User object from the billing email
        $user  = get_user_by( 'email', $order->get_billing_email() );

        // Check that user exist and has a "IPX Customer code"
        if ( $user && isset($user->ipx_customer_code) ) {
            $order->update_meta_data( 'ipx_customer_code', esc_attr($user->ipx_customer_code) ); // Set the IPX code
            $order->save(); // save new meta data
        }
    }
}

实现订单页面编码展示

完成关联后,成功在WooCommerce后台订单页面展示客户编码:

// Display IPX Customer Code on Order screen

add_action( 'woocommerce_admin_order_data_after_billing_address', 'ipx_collection_weight_display_admin_order_meta' );
   
function ipx_collection_weight_display_admin_order_meta( $order ) {    
     
   echo '<p><strong>IPX Customer Code:</strong> ' . get_post_meta( $order->get_id(), 'ipx_customer_code', true ) . '</p>';
     
}

待开发:管理员邮件添加编码

目前正尝试将客户编码添加至管理员邮件,相关代码仍在开发中:

add_action( 'woocommerce_email_order_meta', 'add_ipx_customer_code_to_email', 10, 3 );
function add_ipx_customer_code_to_email( $order, $sent_to_admin, $plain_text ){

    $ipx_customer_code = get_post_meta( $order->get_order_number(), 'ipx_customer_code', true );
    
    // Don't display anything if it is empty
    if( empty( $ipx_customer_code ) )
        return;
    
    if ( $plain_text === false ) {
        echo '<ul>
                <li><strong>IPX Customer Code: </strong>' . $ipx_customer_code . '</li>
            </ul>';
    } else {
        echo "IPX Customer Code: ". $ipx_customer_code; 
    }
    
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:52:42