WooCommerce新订单订单项无法写入客户备注字段问题排查
问题描述
我尝试在WooCommerce新订单的客户备注字段中添加已订购商品(每行显示单个商品的数量),在functions.php中引入以下代码后未生效:
/* Add ordered products to the customer notes field on order creation. */ add_action( ‘woocommerce_new_order’, ‘products_in_customer_notes’, 10, 1 ); function products_in_customer_notes( $order_id ) { $order = wc_get_order( $order_id ); // Verify it's a WC Order if ( is_a( $order, 'WC_Order' ) ) { $customer_note = $order->get_customer_note(); foreach ( $order->get_items() as $item_id => $item ) { $product_name = $item->get_name(); $quantity = $item->get_quantity(); $customer_note .= "<br>"; $customer_note .= $quantity . 'x ' . $product_name; } // Add the note $order->set_customer_note($customer_note); // $order->add_order_note($customer_note); // Save the data $order->save(); } }
当上述代码无效后,我简化代码改用硬编码测试,但仍然无效:
/* Add ordered products to the customer notes field on order creation. */ add_action( ‘woocommerce_new_order’, ‘products_in_customer_notes’, 10, 1 ); function products_in_customer_notes( $order_id ) { $order = wc_get_order( $order_id ); // Verify it's a WC Order if ( is_a( $order, 'WC_Order' ) ) { $customer_note = $order->get_customer_note(); $customer_note .= '<br>'; $customer_note .= 'Hardcoded Test'; // foreach ( $order->get_items() as $item_id => $item ) { // $product_name = $item->get_name(); // $quantity = $item->get_quantity(); // $customer_note .= "<br>"; // $customer_note .= $quantity . 'x ' . $product_name; // } // Add the note $order->set_customer_note($customer_note); // $order->add_order_note($customer_note); // Save the data $order->save(); } }
请问我遗漏了什么导致功能无法正常工作?
期望输出格式如下:
下单时填写的客户备注(如果有的话) 1x 商品A 3x 商品B 8x 商品C ...
问题原因及解决方案
1. 引号格式错误
代码中使用了中文全角引号(例如‘woocommerce_new_order’),但PHP仅识别英文半角引号('woocommerce_new_order'),这会导致钩子无法正确绑定,函数根本不会被触发执行。
2. 钩子时机选择不当
woocommerce_new_order钩子在订单创建的早期阶段触发,此时订单数据可能还未完成全部初始化,手动调用$order->save()可能会覆盖后续的订单更新操作,导致修改的客户备注无法被留存。建议改用woocommerce_checkout_create_order钩子,这个钩子在订单即将创建完成时触发,能确保修改的内容被正确保存。
修正后的代码
/* 在订单创建时将已购商品添加到客户备注字段 */ add_action( 'woocommerce_checkout_create_order', 'products_in_customer_notes', 10, 2 ); function products_in_customer_notes( $order, $data ) { // 获取原客户备注内容 $customer_note = $order->get_customer_note(); // 遍历订单中的商品 foreach ( $order->get_items() as $item ) { $product_name = $item->get_name(); $quantity = $item->get_quantity(); // 使用换行符替代<br>,因为客户备注存储的是纯文本,前端会自动处理换行显示 $customer_note .= "\n" . $quantity . 'x ' . $product_name; } // 更新客户备注 $order->set_customer_note( $customer_note ); // 无需手动调用save(),该钩子会自动处理订单保存 }
额外提示
- 客户备注字段存储的是纯文本,使用
\n换行比<br>更适配,后台和前端显示时会自动转换为可视换行。 - 确保代码添加到当前启用主题的
functions.php文件中,或者使用自定义插件来管理代码,避免主题更新导致代码丢失。
内容的提问来源于stack exchange,提问作者Konstantinos Sakkas
相关产品推荐
相关产品推荐

