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

求助:Woocommerce存档页面产品名称下方添加产品标签(代码失效)

解决WooCommerce产品名称下方添加产品标签的问题

我看了你这段代码,问题主要出在几个细节上,帮你调整并完善下:

原代码的问题点

  • 函数里使用了$post->ID但没有引入全局$post变量,而且其实函数已经传入了$id参数,直接用它更稳妥
  • 没有判断wc_get_product_terms是否返回有效结果,空数组调用array_shift会报错
  • 原代码逻辑不完整(if ...后面没写完),而且如果是想在产品名称下方单独显示标签,用the_title过滤器会把标签和标题合并成一个文本,可能不是你想要的效果

方案1:修正the_title过滤器(把标签追加到标题文本后)

如果确实需要把标签和标题合并显示,可以用下面的修正代码:

/**
 * Add product tag to product title
 */
add_filter( 'the_title', 'mycode_add_tag_to_product_title', 10, 2 );
function mycode_add_tag_to_product_title( $title, $id ) {
    // 只针对产品类型的帖子
    if ( get_post_type( $id ) !== 'product' ) {
        return $title;
    }

    // 获取产品的标签分类术语(直接获取名称更高效)
    $terms = wc_get_product_terms( $id, 'product_tag', array( 'fields' => 'names' ) );
    
    // 如果有标签,追加到标题后(用换行和自定义类方便样式调整)
    if ( ! empty( $terms ) ) {
        $tag_text = implode( ', ', $terms ); // 多个标签用逗号分隔
        $title .= '<br><span class="product-title-tags">' . esc_html( $tag_text ) . '</span>';
    }

    return $title;
}

方案2:用动作钩子在产品名称下方单独显示标签(更推荐)

如果是想在产品标题下方单独展示标签,不修改原标题文本,用WooCommerce的动作钩子更合适,这样不会影响其他地方的产品标题显示:

/**
 * 在单个产品页面的标题下方显示产品标签
 */
add_action( 'woocommerce_single_product_summary', 'mycode_display_tags_below_single_title', 6 );
function mycode_display_tags_below_single_title() {
    global $product;
    
    // 获取产品标签
    $tags = $product->get_tags();
    
    if ( ! empty( $tags ) ) {
        echo '<div class="product-tags-below-title">';
        echo '<span class="tag-label">' . esc_html__( 'Tags:', 'woocommerce' ) . '</span> ';
        // 用WooCommerce内置函数生成标签链接列表
        echo wc_get_product_tag_list( $product->get_id(), ', ', '<span class="tag-links">', '</span>' );
        echo '</div>';
    }
}

// 如果需要在商店列表页面的产品标题下方也显示标签,加上这段
add_action( 'woocommerce_after_shop_loop_item_title', 'mycode_display_tags_below_shop_title', 5 );
function mycode_display_tags_below_shop_title() {
    global $product;
    
    $tags = $product->get_tags();
    
    if ( ! empty( $tags ) ) {
        echo '<div class="shop-product-tags">';
        echo wc_get_product_tag_list( $product->get_id(), ', ', '', '' );
        echo '</div>';
    }
}

补充说明

  • 可以通过自定义CSS调整标签的样式,比如针对.product-tags-below-title或.shop-product-tags类设置字体大小、颜色、间距等
  • 方案2的钩子优先级:单个产品页面中标题的优先级是5,设置为6会确保标签在标题之后显示;商店列表中价格的优先级是10,设置为5会让标签在价格之前显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:38:36