如何在WooCommerce订单客户备注中添加YITH Product Addons产品选项?
解决YITH Product Addons选项加入WooCommerce订单备注的方案
核心问题说明
YITH Product Addons的附加选项不存于常规元数据字段,直接用get_meta_data()拿不到有效内容,得针对YITH的存储逻辑来获取。
直接可用的代码方案
把下面代码加到主题的functions.php或者自定义插件里,结账时会自动把附加选项追加到订单备注:
add_action( 'woocommerce_checkout_update_order_meta', 'add_yith_addons_to_order_notes', 10, 1 ); function add_yith_addons_to_order_notes( $order_id ) { $order = wc_get_order( $order_id ); $addons_notes = ''; // 遍历订单里的每个商品 foreach ( $order->get_items() as $item_id => $item ) { // 读取YITH附加选项的专属元数据 $addons = $item->get_meta( '_yith_wapo_addons', true ); if ( ! empty( $addons ) ) { $product_name = $item->get_name(); $addons_notes .= "\n" . $product_name . ' (数量: ' . $item->get_quantity() . ') 的附加选项:'; // 格式化选项内容,兼容预设选项和自定义输入 foreach ( $addons as $addon ) { if ( isset( $addon['value'] ) ) { $addons_notes .= "\n- " . $addon['name'] . ': ' . $addon['value']; } elseif ( isset( $addon['user_value'] ) ) { $addons_notes .= "\n- " . $addon['name'] . ': ' . $addon['user_value']; } } } } // 把附加选项内容追加到原订单备注 if ( ! empty( $addons_notes ) ) { $current_notes = $order->get_customer_note(); $new_notes = $current_notes . $addons_notes; $order->set_customer_note( $new_notes ); $order->save(); } }
代码逻辑解释
- 用
woocommerce_checkout_update_order_meta钩子,在订单生成时触发操作 - 通过
_yith_wapo_addons这个YITH专属元键,直接读取商品项的附加选项数据 - 区分预设选项(比如颜色、款式)和自定义输入(比如定制文字),统一格式输出
- 把处理好的选项内容追加到用户原有的订单备注里,保存更新订单
备用方案(如果上面的代码无效)
要是_yith_wapo_addons元键读不到数据,试试用YITH官方提供的函数来获取:
add_action( 'woocommerce_checkout_update_order_meta', 'add_yith_addons_to_order_notes_alt', 10, 1 ); function add_yith_addons_to_order_notes_alt( $order_id ) { // 先检查YITH类是否存在,避免报错 if ( ! class_exists( 'YITH_WAPO_Frontend' ) ) return; $order = wc_get_order( $order_id ); $addons_notes = ''; foreach ( $order->get_items() as $item_id => $item ) { $product = $item->get_product(); // 用YITH的函数获取商品的附加选项配置 $addons = YITH_WAPO_Frontend()->get_product_addons( $product->get_id() ); if ( ! empty( $addons ) ) { $product_name = $item->get_name(); $addons_notes .= "\n" . $product_name . ' (数量: ' . $item->get_quantity() . ') 的附加选项:'; foreach ( $addons as $addon ) { // 读取用户选择的对应选项值 $selected_value = $item->get_meta( '_yith_wapo_addon_' . $addon['id'], true ); if ( ! empty( $selected_value ) ) { $addons_notes .= "\n- " . $addon['name'] . ': ' . $selected_value; } } } } if ( ! empty( $addons_notes ) ) { $current_notes = $order->get_customer_note(); $new_notes = $current_notes . $addons_notes; $order->set_customer_note( $new_notes ); $order->save(); } }
内容的提问来源于stack exchange,提问作者Deyv
相关产品推荐
相关产品推荐

