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

WooCommerce拍卖商品结束时替换分类的代码优化求助

解决WooCommerce拍卖商品到期后替换为指定分类的问题

需求:当WooCommerce拍卖商品结束时间到期后,移除商品所有现有分类,仅保留「Auction ended」分类,避免商品出现在不需要的轮播组件中。现有代码仅能添加该分类,无法移除原有分类。

修改后的代码

function auction_end_date_countdown() {
    global $product;
    $product = apply_filters( 'yith_wcact_get_auction_product', $product );

    ob_start();

    if ( 'auction' === $product->get_type() ) { 
        $dateclose = $product->get_end_date();
        
        if ( $dateclose ) {
            $today = date("Y-m-d H:i:s");                                   
            $format_date = get_option( 'yith_wcact_general_date_format', 'Y-m-d H:i:s' );
            $date = date( 'Y-m-d H:i:s', $dateclose );
            
            if ($today < $date) {
                echo $date;
            } else {
                echo $today;
                
                $term_name = 'Auction ended';
                // 获取目标分类ID,同时检查分类是否存在
                $term = get_term_by( 'name', $term_name, 'product_cat' );
                
                if ( $term && ! is_wp_error( $term ) ) {
                    $term_id = $term->term_id;
                    // 获取当前商品已有的分类ID
                    $current_cats = $product->get_category_ids();
                    
                    // 检查是否已经只保留了目标分类,避免重复执行保存操作
                    if ( count($current_cats) !== 1 || ! in_array($term_id, $current_cats) ) {
                        // 直接设置为仅包含目标分类的数组,替换原有所有分类
                        $product->set_category_ids( [$term_id] );
                        $product->save();
                    }
                }
            }
        }
    }

    $html = ob_get_clean();
    return $html;
}
add_shortcode( 'veiling_eind_datum_aftellen', 'auction_end_date_countdown' );

关键修改说明

  • 替换原有分类逻辑:将原来的追加分类ID改为直接传入仅包含「Auction ended」分类ID的数组,彻底覆盖商品所有原有分类
  • 增加分类存在性校验:避免因分类不存在导致的PHP报错,提升代码稳定性
  • 减少重复操作:检查商品当前分类状态,仅在不符合要求时执行保存操作,降低数据库写入频率
  • 优化代码冗余:移除重复的global $product声明,精简代码结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:50:10