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
相关产品推荐
相关产品推荐

