在WooCommerce订单详情页及邮件中显示产品变体属性
在WooCommerce订单详情页和邮件通知中显示产品变体属性
要实现和购物车页面一致的变体属性显示效果,你可以通过添加自定义代码到主题的functions.php文件或使用代码片段插件完成,具体方案如下:
方案一:在产品名称后追加变体属性
添加以下代码,它会在订单详情页和邮件通知的产品名称下方,以列表形式展示变体属性:
/** * 在订单详情页和邮件中显示产品变体属性 */ function display_variation_attributes_in_orders($item_name, $item) { // 仅处理变体产品 if ($item->get_product() && $item->get_product()->is_type('variation')) { $product = $item->get_product(); $variation_attributes = $product->get_variation_attributes(); if (!empty($variation_attributes)) { $attributes_html = '<ul class="variation-attributes">'; foreach ($variation_attributes as $attribute => $value) { // 提取并格式化属性名称 $attribute_label = wc_attribute_label(str_replace('attribute_', '', $attribute)); $attributes_html .= "<li><strong>{$attribute_label}:</strong> {$value}</li>"; } $attributes_html .= '</ul>'; // 将属性追加到产品名称后 $item_name .= $attributes_html; } } return $item_name; } add_filter('woocommerce_order_item_name', 'display_variation_attributes_in_orders', 10, 2);
方案二:自定义变体属性的显示样式
如果希望变体属性的展示风格更贴近购物车页面,可通过修改订单项目元数据的渲染逻辑实现:
/** * 调整订单项目中变体属性的显示样式 */ function customize_variation_meta_display($html, $item, $args) { if ($item->get_product() && $item->get_product()->is_type('variation')) { $product = $item->get_product(); $variation_attributes = $product->get_variation_attributes(); if (!empty($variation_attributes)) { $html = ''; foreach ($variation_attributes as $attribute => $value) { $attribute_label = wc_attribute_label(str_replace('attribute_', '', $attribute)); $html .= "<div class='variation'><strong>{$attribute_label}:</strong> {$value}</div>"; } } } return $html; } add_filter('woocommerce_display_item_meta', 'customize_variation_meta_display', 10, 3);
注意事项
- 代码添加建议:优先使用代码片段插件(如Code Snippets)添加代码,避免直接修改主题文件导致更新时代码丢失。
- 样式自定义:若需调整属性的显示样式,可通过CSS针对
.variation-attributes或.variation类修改样式。 - 版本兼容性:上述代码在WooCommerce 3.0及以上版本中测试有效,确保你的WooCommerce为最新稳定版。
内容的提问来源于stack exchange,提问作者TravisScott
相关产品推荐
相关产品推荐

