You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Woocommerce购物车首个商品无法仅显示内容首段问题排查

解决WooCommerce购物车首个商品显示全部内容的问题

问题描述

需要在WooCommerce购物车页面的商品名称下方显示对应商品内容的首段文本,目前所有商品均能正常仅显示首段,唯独购物车列表中的首个商品会显示全部内容。更换默认主题后问题仍存在,希望通过钩子而非模板重写解决。

原实现代码

// Add a SUBTITLE to the cart items below product title
add_action('woocommerce_after_cart_item_name', 'add_custom_subtitle_after_cart_item_name', 0, 1);
function add_custom_subtitle_after_cart_item_name($cart_item)
{
    //Get the product content and then extract the first paragraph
    $content = get_post($cart_item['product_id'])->post_content;

    $filtered_content = apply_filters('the_content', $content);

    $filtered_content = explode('</p>', $filtered_content);
    $filtered_content = array_slice($filtered_content, 0,  1);
    $filtered_content = implode('</p>',  $filtered_content);

    if ($filtered_content) {
        echo '<div class="custom-woo-cart__item-subtitle">' . $filtered_content . '</div>';
    }
}

问题根源

测试发现移除apply_filters('the_content', $content)后改用自定义文本测试,问题消失。进一步确认:the_content过滤器的缓存机制导致首个商品的内容未触发自动段落转换(wpautop),没有生成<p>...</p>标签,使得后续按</p>分割段落的逻辑完全失效,最终输出全部内容。

修复方案

通过手动强制生成段落标签+使用DOM解析提取首段的方式解决,代码如下:

// Add a SUBTITLE to the cart items below product title
add_action('woocommerce_after_cart_item_name', 'add_custom_subtitle_after_cart_item_name', 10, 1);
function add_custom_subtitle_after_cart_item_name($cart_item)
{
    // 验证商品post对象有效性
    $product_post = get_post($cart_item['product_id']);
    if (!$product_post) return;
    
    $content = $product_post->post_content;
    // 应用内容过滤器后,强制调用wpautop生成段落标签
    $filtered_content = apply_filters('the_content', $content);
    $filtered_content = wpautop($filtered_content, true);

    // 使用DOMDocument解析HTML,可靠提取第一个<p>标签内容
    $dom = new DOMDocument();
    // 处理UTF-8编码问题,抑制解析警告
    @$dom->loadHTML(mb_convert_encoding($filtered_content, 'HTML-ENTITIES', 'UTF-8'));
    
    $paragraphs = $dom->getElementsByTagName('p');
    if ($paragraphs->length > 0) {
        $first_paragraph = $dom->saveHTML($paragraphs->item(0));
        echo '<div class="custom-woo-cart__item-subtitle">' . $first_paragraph . '</div>';
    }
}

关键修复点

  • 增加get_post有效性判断,避免空值引发报错
  • 手动调用wpautop强制生成段落标签,绕过缓存导致的格式异常
  • 使用DOM解析替代字符串分割,更稳定地提取首段内容,兼容各种HTML格式情况
  • 调整钩子优先级为默认的10,避免过早执行导致过滤器未完全加载

内容的提问来源于stack exchange,提问作者Davood Kazemi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:45:34