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

WooCommerce商品由缺货转为有货时如何显示自定义补货徽章

WooCommerce 商品补货徽章实现方案(解决库存修改误触发问题)

现有使用get_date_modified()的方案存在缺陷:商品任意字段修改(包括价格、描述、库存调整)都会更新该字段时间,会误触发徽章显示,无法满足仅在缺货转有货时展示补货徽章的需求。


解决思路

  • 新增自定义字段存储商品「缺货转有货的实际时间」,仅当库存状态从outofstock切换为instock时才更新该字段值
  • 展示补货徽章时读取该自定义字段的时间判断是否在10天有效期内
  • 可通过调整钩子优先级避免和原有新品徽章展示冲突

完整实现代码

1. 监听库存状态变化,保存补货时间

// 仅在商品从缺货切换为有货时,记录补货时间到自定义字段
add_action( 'woocommerce_product_set_stock_status', function( $product_id, $new_status, $old_status ) {
    if ( $old_status === 'outofstock' && $new_status === 'instock' ) {
        update_post_meta( $product_id, '_back_in_stock_time', current_time( 'timestamp' ) );
    }
}, 10, 3 );

2. 前端展示补货徽章

add_action( 'woocommerce_before_shop_loop_item_title', function() {      
    global $product;
    $display_days = 10;
    $back_in_stock_time = get_post_meta( $product->get_id(), '_back_in_stock_time', true );
    
    // 判断条件:有补货记录、在有效期内、非促销状态、有库存、未设置自定义徽章
    if ( 
        $back_in_stock_time &&
        ( time() - ( 60 * 60 * 24 * $display_days ) ) < $back_in_stock_time && 
        !$product->is_on_sale() && 
        $product->is_in_stock() && 
        get_post_meta( $product->get_id(), 'custom_badge', true) !== 'yes' 
    ) {
        echo '<div class="badge_loop_wrapper"><img src="https://xxxx.ch/wp-content/uploads/2021/01/back_in_stock_badge.png" alt="补货徽章"/></div>';
    }
}, 20 ); // 优先级设为20,晚于默认的新品徽章,确保新品徽章展示优先级更高

可选优化建议

如果需要严格按照商品发布时间计算新品有效期,可将原有新品徽章代码中的$product->get_date_modified()替换为$product->get_date_published(),避免商品后续修改信息导致新品徽章重新计时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:54:03