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

基于ACF字段自定义日期修改WooCommerce订单状态

WooCommerce订单按ACF存储的日期自动修改状态

需求背景

给WooCommerce订单添加了ACF文本字段(字段ID为reminder),存储格式为d/m/Y的提醒发送日期,需要在该日期自动将订单状态改为wc-reminder-sent,同时标记已处理避免重复操作。

修改后的代码

function order_status_changer() {
    // 生成和ACF字段格式一致的今日日期字符串
    $today_date = date('d/m/Y');

    $args = array(
        'meta_query' => array(
            'relation' => 'AND',
            // 匹配ACF字段中存储的日期等于今天的订单
            array(
                'key'     => 'reminder',
                'value'   => $today_date,
                'compare' => '='
            ),
            // 排除已经标记为提醒已发送的订单
            array(
                'key'     => '_reminder_sent',
                'compare' => 'NOT EXISTS'
            )
        ),
        'posts_per_page' => -1,
        'post_type'      => 'shop_order',
        'post_status'    => 'wc-processing', // 仅处理处于processing状态的订单
    );

    $order_query = new WP_Query($args);

    foreach ($order_query->posts as $post_item) {
        // 使用WooCommerce推荐的方式获取订单对象
        $order = wc_get_order($post_item->ID);
        if (!$order) continue;

        // 更新订单状态并添加备注
        $order->update_status('wc-reminder-sent', '系统自动标记:已发送提醒');
        // 添加元数据标记,防止重复处理
        update_post_meta($post_item->ID, '_reminder_sent', 1);
    }
}

// 推荐通过WP Cron定时执行,每天运行一次
// add_action('daily_reminder_order_trigger', 'order_status_changer');
// if (!wp_next_scheduled('daily_reminder_order_trigger')) {
//     wp_schedule_event(time(), 'daily', 'daily_reminder_order_trigger');
// }

关键修改说明

  • 移除了原代码中无用的$wpdb查询和基于post_modified_gmt的date_query,改为直接匹配ACF字段reminder的日期值
  • 统一日期格式为d/m/Y,确保和ACF字段存储的格式一致,避免匹配错误
  • 使用wc_get_order()替代旧的new WC_Order(),符合WooCommerce最新开发规范
  • 增加订单对象存在性判断,提升代码稳定性
  • 附带了WP Cron定时触发的配置代码,建议开启后让系统每天自动执行,无需手动调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:23:11