如何在Woocommerce购物车页面显示产品变体自定义字段值
解决WooCommerce变体产品自定义字段在购物车显示的问题
我帮你梳理下具体的实现步骤,你只需要在functions.php里添加对应的代码,再配合模板调整就能搞定:
1. 把变体自定义字段值同步到购物车项目
首先得让购物车项目能“携带”这个自定义字段的值,用woocommerce_add_cart_item_data钩子来实现:
// 将变体自定义字段值存入购物车项目数据 add_filter( 'woocommerce_add_cart_item_data', 'save_variation_custom_field_to_cart', 10, 3 ); function save_variation_custom_field_to_cart( $cart_item_data, $product_id, $variation_id ) { // 替换成你实际的自定义字段键名,比如你之前设置的'_my_variation_custom_field' $custom_field_key = '_my_variation_custom_field'; if ( $variation_id > 0 ) { $custom_field_value = get_post_meta( $variation_id, $custom_field_key, true ); if ( ! empty( $custom_field_value ) ) { // 存入购物车数据,加唯一键避免相同产品合并时丢失字段值 $cart_item_data[ $custom_field_key ] = $custom_field_value; $cart_item_data['unique_variation_key'] = md5( microtime() . rand() ); } } return $cart_item_data; }
2. (可选)同步字段值到订单项目
如果希望这个字段值也能在订单详情里显示,加上这段代码,后续订单里就能看到:
// 将自定义字段值同步到订单项目 add_action( 'woocommerce_checkout_create_order_line_item', 'add_variation_custom_field_to_order', 10, 4 ); function add_variation_custom_field_to_order( $item, $cart_item_key, $values, $order ) { $custom_field_key = '_my_variation_custom_field'; if ( isset( $values[ $custom_field_key ] ) ) { // 第一个参数是显示在订单里的字段名称,可自定义 $item->add_meta_data( '专属规格', $values[ $custom_field_key ], true ); } }
3. 在购物车页面显示字段值
这里有两种方式,选你方便的来:
方式一:用钩子自动输出(不用改模板)
不想动模板文件的话,用钩子直接把字段值加到购物车项目名称下方:
// 在购物车项目中显示自定义字段 add_filter( 'woocommerce_cart_item_name', 'display_variation_custom_field_in_cart', 10, 3 ); function display_variation_custom_field_in_cart( $product_name, $cart_item, $cart_item_key ) { $custom_field_key = '_my_variation_custom_field'; if ( isset( $cart_item[ $custom_field_key ] ) ) { $product_name .= '<br><small style="color:#666;">' . __('专属规格:', 'woocommerce') . $cart_item[ $custom_field_key ] . '</small>'; } return $product_name; }
方式二:直接修改cart.php模板(更灵活控制位置)
如果你想精准控制显示位置,先把WooCommerce的cart.php模板复制到主题的woocommerce/cart目录下(避免插件更新覆盖修改),然后在购物车项目循环里(foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )这段代码内部)找合适的位置添加:
<?php $custom_field_key = '_my_variation_custom_field'; if ( isset( $cart_item[ $custom_field_key ] ) ) { echo '<p class="variation-custom-field" style="margin:0.5em 0;">' . __('专属规格:', 'woocommerce') . esc_html( $cart_item[ $custom_field_key ] ) . '</p>'; } ?>
注意事项
- 记得把所有代码里的
_my_variation_custom_field替换成你实际使用的自定义字段键名,要和你之前后台添加字段时的键名完全一致; - 修改模板时一定要用主题子目录的woocommerce文件夹来覆盖,不要直接改插件自带的模板;
- 如果你的自定义字段是多选、文件上传这类复杂类型,需要调整获取和输出的逻辑,确保数据正确显示。
内容的提问来源于stack exchange,提问作者Bradley
相关产品推荐
相关产品推荐

