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

如何在WordPress/WooCommerce标题中添加Span标签?

实现WordPress/WooCommerce标题拆分并添加标签的方案

核心思路

通过WordPress的标题过滤钩子,识别标题中用-(空格+连字符+空格)分隔的两部分,将后半部分包裹到带superspan类的<span>标签中,同时移除分隔符。

代码实现

将以下代码添加到当前激活主题的functions.php文件,或使用自定义代码插件(如Code Snippets)插入:

add_filter('the_title', 'wrap_title_part_in_span', 10, 2);

function wrap_title_part_in_span($title, $id) {
    // 仅对WooCommerce产品相关页面生效(可根据需求修改或移除该判断)
    $post_type = get_post_type($id);
    if ($post_type !== 'product' && !is_singular('product') && !is_shop()) {
        return $title;
    }

    // 检查标题是否包含指定分隔符
    if (strpos($title, ' - ') !== false) {
        // 拆分标题为两部分(仅拆分第一次出现的分隔符)
        list($prefix, $suffix) = explode(' - ', $title, 2);
        // 重新拼接并添加span标签
        $title = trim($prefix) . ' <span class="superspan">' . trim($suffix) . '</span>';
    }

    return $title;
}

使用说明

  1. 标题格式要求:编辑产品标题时,用-分隔前后部分,例如输入Chocolate spread 13 oz - Nutella,前端会输出:
    <h1>Chocolate spread 13 oz <span class="superspan">Nutella</span></h1>
    
  2. 范围调整:如果需要让该功能对所有页面标题生效,直接删除代码中关于post_type的判断逻辑即可。
  3. 样式自定义:可以通过自定义CSS为superspan类添加样式,示例:
    .superspan {
        font-weight: 700;
        color: #2c3e50;
        /* 其他样式属性 */
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:47:17