WooCommerce按商品类别在购物车、感谢页及邮件显示自定义文本
WooCommerce 按商品类别显示自定义文本(购物车/感谢页/邮件)
你的代码存在几个关键问题导致无法正常运行,同时未覆盖感谢页和邮件通知的需求,以下是修复后的完整解决方案:
问题分析
- 仅处理了购物车页面,未实现感谢页和邮件的文本展示
- 获取产品分类时,直接使用变体ID(可变产品场景)会丢失父产品的分类信息
- 核心逻辑未封装,无法在多个场景复用
修复后的完整代码
// 封装核心函数:根据购物车/订单获取对应分类的自定义文本 function get_custom_category_texts($order = null) { // 定义分类slug与对应文本的映射(请替换为你的实际分类slug和文本) $categories_and_texts = array( 'category-slug-1' => '这是分类1的自定义文本', 'category-slug-2' => '这是分类2的自定义文本', 'category-slug-3' => '这是分类3的自定义文本', // 可继续添加更多分类 ); $categories_in_cart = array(); // 处理购物车场景 if (!$order && WC()->cart && !WC()->cart->is_empty()) { foreach (WC()->cart->get_cart() as $cart_item) { // 优先使用产品ID(避免变体ID导致分类获取失败) $product_id = $cart_item['product_id']; $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'slugs')); foreach ($product_categories as $slug) { if (array_key_exists($slug, $categories_and_texts) && !in_array($slug, $categories_in_cart)) { $categories_in_cart[] = $slug; } } } } // 处理订单场景(感谢页/邮件) elseif ($order) { foreach ($order->get_items() as $item) { $product_id = $item->get_product_id(); $product_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'slugs')); foreach ($product_categories as $slug) { if (array_key_exists($slug, $categories_and_texts) && !in_array($slug, $categories_in_cart)) { $categories_in_cart[] = $slug; } } } } // 组装最终文本 if (!empty($categories_in_cart)) { $output = '<p>注意:你的购物车中包含以下类别的商品:</p>'; foreach ($categories_in_cart as $slug) { $output .= '<p>' . $categories_and_texts[$slug] . '</p>'; } return $output; } return ''; } // 购物车页面显示自定义文本 add_action('woocommerce_before_cart', 'display_custom_text_on_cart'); function display_custom_text_on_cart() { echo get_custom_category_texts(); } // 感谢页(订单收到页)显示自定义文本 add_action('woocommerce_thankyou', 'display_custom_text_on_thankyou'); function display_custom_text_on_thankyou($order_id) { $order = wc_get_order($order_id); echo get_custom_category_texts($order); } // 邮件通知中插入自定义文本 add_action('woocommerce_email_order_details', 'display_custom_text_in_email', 20, 4); function display_custom_text_in_email($order, $sent_to_admin, $plain_text, $email) { // 仅给客户发送的邮件显示(可根据需求调整) if (!$sent_to_admin) { $custom_text = get_custom_category_texts($order); if ($custom_text) { if ($plain_text) { // 纯文本邮件格式转换 $custom_text = strip_tags($custom_text); $custom_text = str_replace('<p>', '', $custom_text); $custom_text = str_replace('</p>', "\n", $custom_text); echo "\n" . $custom_text . "\n"; } else { echo $custom_text; } } } }
使用说明
- 将代码添加到你的主题
functions.php文件或自定义插件中 - 修改
$categories_and_texts数组中的分类slug和对应文本,替换为你实际的分类标识和内容 - 测试三个场景:添加对应分类商品到购物车、完成订单查看感谢页、查看订单通知邮件
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

