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

如何在WooCommerce产品标题前显示shipment-status自定义分类并为术语加不同类

解决方案

你可以直接读取术语的别名(slug)或ID拼接成动态类名,别名本身是WordPress自动生成的合法字符串,不会出现特殊字符,更适合用来写CSS样式,修改后的代码如下:

// 同时挂载商品归档页、单产品页钩子
add_action( 'woocommerce_before_shop_loop_item_title', 'add_shipment_status_term');
// 单产品页优先级设为4,默认标题优先级为5,保证显示在标题上方
add_action( 'woocommerce_single_product_summary', 'add_shipment_status_term', 4 );

function add_shipment_status_term() {
    $terms = wp_get_post_terms(get_the_ID(), 'shipment-status');
    if (!is_wp_error($terms) && !empty($terms)) {
        $current_term = $terms[0];
        // 用术语别名生成动态类名
        $dynamic_class = 'shipment-status-' . $current_term->slug;
        ?>
        <div class="shipment-status <?php echo esc_attr($dynamic_class); ?>">
            <a href="<?php echo esc_url(get_term_link($current_term)); ?>">
                <?php echo esc_html($current_term->name); ?>
            </a>
        </div>
    <?php }
}

样式配置示例

假设你两个术语的别名分别为shipped-from-abroad和available-now,可以直接用生成的类名写差异化样式:

/* 海外发货状态样式 */
.shipment-status-shipped-from-abroad {
    background: #fff2f2;
    color: #ed4c4c;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 12px;
    display: inline-block;
    margin-bottom: 8px;
}

/* 现货状态样式 */
.shipment-status-available-now {
    background: #ecf7ff;
    color: #2d85f0;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 12px;
    display: inline-block;
    margin-bottom: 8px;
}

如果需要用术语ID生成类名,只需要把生成动态类名的代码替换为:

$dynamic_class = 'shipment-status-' . $current_term->term_id;

你可以在后台编辑术语的页面URL中查看对应术语的ID值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:36:06