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

WooCommerce Blocks:为所有商品网格添加NEW标识问题求助

WooCommerce Blocks商品网格添加NEW标识代码修复方案

代码不生效核心原因

  • 回调函数名不匹配:add_filter中注册的回调函数名为add_new_woocommerce_blocks_product_grid_item_html,但实际定义的函数名多了_desc后缀,二者不一致导致钩子没有被正确触发,代码无法执行。
  • 缺少异常判断:未对strpos查找不到</a>标签的情况做兼容,极端场景下会报错。
  • 可选优化点:原代码会给所有商品统一添加NEW标识,没有新品筛选逻辑。

修复后可用代码

add_filter('woocommerce_blocks_product_grid_item_html', 'add_new_woocommerce_blocks_product_grid_item_html', 10 , 3);
function add_new_woocommerce_blocks_product_grid_item_html($content, $data, $product) {
    // 可选逻辑:仅给上架30天内的商品添加NEW标识,不需要可直接删除这段判断
    $published_date = $product->get_date_created();
    $cutoff_date = new DateTime('-30 days');
    if ($published_date < $cutoff_date) {
        return $content;
    }

    $new_badge = '<span class="new-badge onsale">' . esc_html__( 'NEW', 'woocommerce' ) . '</span>';
    $after_link_pos = strpos($content, "</a>");
    // 兼容找不到</a>标签的特殊场景
    if ($after_link_pos === false) {
        return $content;
    }
    $before = substr($content, 0, $after_link_pos + 4);
    $after = substr($content, $after_link_pos + 4);

    $content = $before . $new_badge . $after;

    return $content;
}

配套显示样式参考

将以下代码添加到主题自定义CSS面板,即可正常显示NEW标识:

/* 商品卡片设置相对定位作为标识的定位参照物 */
.wc-block-grid__product {
    position: relative;
}
.new-badge {
    position: absolute;
    top: 12px;
    left: 12px;
    background: #27ae60;
    color: #ffffff;
    padding: 4px 10px;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 700;
    z-index: 9;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:45:05