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

如何实现WooCommerce已售商品30天后自动重新上架?

实现已售商品30天后自动重新上架的WordPress方案

插件方案

  • WooCommerce Scheduler:针对WooCommerce商品的专属调度工具,在商品编辑页就能找到调度设置项,可直接配置商品下架后30天自动上架的规则,无需额外代码。
  • Advanced Post Scheduler:支持包括WooCommerce商品在内的所有自定义文章类型的上架/下架调度。售出商品时手动标记下架,再设置30天后的自动上架时间,操作简单直观。

代码片段方案(适用于WooCommerce环境)

如果不想依赖插件,可将以下代码添加到主题的functions.php文件或自定义代码插件中,实现订单完成后30天自动恢复对应商品上架:

// 订单完成时记录商品售出时间并下架
add_action('woocommerce_order_status_completed', 'record_sold_product_info', 10, 1);
function record_sold_product_info($order_id) {
    $order = wc_get_order($order_id);
    foreach ($order->get_items() as $item) {
        $product_id = $item->get_product_id();
        // 存储售出时间戳到商品自定义字段
        update_post_meta($product_id, '_sold_timestamp', current_time('timestamp'));
        // 将商品设为草稿状态实现下架
        wp_update_post(array(
            'ID' => $product_id,
            'post_status' => 'draft'
        ));
    }
}

// 每日检查并恢复符合条件的商品上架
add_action('wp', 'restore_products_after_30_days');
function restore_products_after_30_days() {
    // 24小时内仅执行一次,避免资源浪费
    if (!get_transient('product_restore_cron')) {
        $query_args = array(
            'post_type' => 'product',
            'post_status' => 'draft',
            'meta_key' => '_sold_timestamp',
            'posts_per_page' => -1
        );
        $sold_products = new WP_Query($query_args);

        if ($sold_products->have_posts()) {
            while ($sold_products->have_posts()) {
                $sold_products->the_post();
                $sold_time = get_post_meta(get_the_ID(), '_sold_timestamp', true);
                $restore_time = $sold_time + (30 * 24 * 60 * 60);
                
                if (current_time('timestamp') >= $restore_time) {
                    // 恢复商品为发布状态
                    wp_update_post(array(
                        'ID' => get_the_ID(),
                        'post_status' => 'publish'
                    ));
                    // 删除已处理的时间标记
                    delete_post_meta(get_the_ID(), '_sold_timestamp');
                }
            }
            wp_reset_postdata();
        }
        set_transient('product_restore_cron', true, 24 * 60 * 60);
    }
}

代码说明

  • 订单标记为「已完成」时,自动记录每个商品的售出时间,并将商品设为草稿状态实现下架。
  • 系统每日自动检查一次所有已售出商品,若距离售出时间已满30天,则将商品恢复为发布状态(上架)。
  • 若你的商品是可变产品(Variation),只需将代码中的$product_id = $item->get_product_id()改为$product_id = $item->get_variation_id(),同时调整查询参数适配可变产品即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:54:16