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

如何自定义WooCommerce单产品页面的产品标签显示样式?

自定义WooCommerce单产品页面产品标签显示结构

当前产品标签HTML结构

<span class="tagged_as">All tags: <span class="tagged_as">
<a href="" rel="tag">000</a>, 
<a href="" rel="tag">100</a>, 
<a href="" rel="tag">200</a>, 
<a href="" rel="tag">300</a>, 
<a href="" rel="tag">400</a>, 
<a href="" rel="tag">500</a>, 
<a href="" rel="tag">600</a>, 
<a href="" rel="tag">700</a>
</span></span>

目标结构

<span class="tagged_as">All tags: <span class="tagged_as">
<a href="" rel="tag"><span>#</span>000</a>, 
<a href="" rel="tag"><span>#</span>100</a>, 
<a href="" rel="tag"><span>#</span>200</a>, 
<a href="" rel="tag"><span>#</span>300</a>, 
<a href="" rel="tag"><span>#</span>400</a>, 
<a href="" rel="tag"><span>#</span>500</a>, 
<a href="" rel="tag"><span>#</span>600</a>, 
<a href="" rel="tag"><span>#</span>700</a>
</span></span>

无效的尝试代码

function custom_product_tag_output( $tag_list ) {
    // 如果存在标签,在每个标签前添加"#"符号
    if ( $tag_list ) {
        // 使用正则表达式在每个标签前添加"#"符号
        $tag_list = preg_replace_callback(
            '/(&lt;a[^&gt;]+&gt;)(.*?)(&lt;/a&gt;)/',
            function($matches) {
                return $matches[1] . '&lt;span&gt;#&lt;/span&gt;' . $matches[2] . $matches[3];
            },
            $tag_list
        );
        // 添加span包裹层
        $tag_list = '&lt;span class=&quot;tagged_as&quot;&gt;' . $tag_list . '&lt;/span&gt;';
    }

    return $tag_list;
}
add_filter( 'woocommerce_product_tag_list', 'custom_product_tag_output', 10, 1 );

正确解决方案

之前的代码无效原因:woocommerce_product_tag_list钩子处理的是整个标签列表的最终HTML,此时传入的$tag_list已经是转义后的实体字符(比如&lt;a&gt;而非<a>),正则无法匹配到实际的标签结构,而且额外添加的span会导致结构重复。

正确的做法是针对单个标签项进行修改,使用woocommerce_product_tag_list_item钩子,这个钩子会传入每个标签的HTML、标签对象和参数,能精准修改每个标签的内容:

function add_hash_prefix_to_product_tags( $item_html, $term, $args ) {
    // 在标签名称前插入带#的span元素
    return str_replace( $term->name, '<span>#</span>' . $term->name, $item_html );
}
add_filter( 'woocommerce_product_tag_list_item', 'add_hash_prefix_to_product_tags', 10, 3 );

代码说明

  • woocommerce_product_tag_list_item:WooCommerce提供的用于修改单个产品标签HTML的钩子,优先级设为10,接收3个参数:单个标签的HTML、标签术语对象、输出参数。
  • str_replace:直接替换标签名称,在其前插入<span>#</span>,确保每个标签文本前都带有指定的span结构。
  • 该方法无需处理整个列表的正则匹配,更高效且不易出错,同时不会破坏原有的标签列表包裹结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:43:25