如何在WooCommerce中实现下单1天后自动将订单状态从processing改为Preparing?
在WooCommerce中实现订单下单1天后自动变更状态的方案
前提说明
WooCommerce默认没有Preparing(准备中)这个订单状态,所以需要先注册该自定义状态,再实现自动更新逻辑。
1. 注册自定义订单状态
将以下代码添加到当前主题的functions.php文件,或自定义功能插件中:
// 注册自定义订单状态 add_action('init', 'register_preparing_order_status'); function register_preparing_order_status() { register_post_status('wc-preparing', array( 'label' => '准备中', 'public' => true, 'exclude_from_search' => false, 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, 'label_count' => _n_noop('准备中 (%s)', '准备中 (%s)') )); } // 将自定义状态添加到WooCommerce订单状态下拉列表 add_filter('wc_order_statuses', 'add_preparing_to_order_statuses'); function add_preparing_to_order_statuses($order_statuses) { $new_order_statuses = array(); // 在"处理中"状态后插入自定义状态 foreach ($order_statuses as $key => $status) { $new_order_statuses[$key] = $status; if ('wc-processing' === $key) { $new_order_statuses['wc-preparing'] = '准备中'; } } return $new_order_statuses; }
这段代码会在后台订单状态列表和下拉选择框中添加"准备中"状态。
2. 实现定时自动更新订单状态
利用WordPress的Cron定时任务,每天执行一次检查,将下单超过1天的processing状态订单改为Preparing:
// 激活主题/插件时设置定时任务 register_activation_hook(__FILE__, 'setup_daily_order_status_cron'); function setup_daily_order_status_cron() { if (!wp_next_scheduled('update_processing_to_preparing')) { // 每天执行一次,可按需调整时间间隔 wp_schedule_event(time(), 'daily', 'update_processing_to_preparing'); } } // 定时任务回调函数 add_action('update_processing_to_preparing', 'update_processing_orders_to_preparing'); function update_processing_orders_to_preparing() { // 查询所有处理中的订单,过滤下单超过1天的记录 $args = array( 'post_type' => 'shop_order', 'post_status' => 'wc-processing', 'posts_per_page' => -1, 'date_query' => array( array( 'column' => 'post_date_gmt', 'before' => '1 day ago', 'inclusive' => true ) ) ); $orders = get_posts($args); foreach ($orders as $order_post) { $order = wc_get_order($order_post->ID); if ($order) { // 更新订单状态并添加日志备注 $order->update_status('preparing', '下单超过1天,自动变更为准备中'); } } } // 停用主题/插件时清除定时任务 register_deactivation_hook(__FILE__, 'clear_daily_order_status_cron'); function clear_daily_order_status_cron() { wp_clear_scheduled_hook('update_processing_to_preparing'); }
代码说明:
- 测试时可将
daily改为hourly,快速验证逻辑,测试完成后改回daily。 - 使用
post_date_gmt避免时区差异导致的时间判断错误。 - 更新状态时添加的备注,可在后台订单日志中查看变更原因。
3. 注意事项
- 不要直接修改WooCommerce核心文件,推荐放在子主题
functions.php或自定义插件中,避免主题更新丢失代码。 - 若定时任务未触发,检查WordPress的Cron是否正常运行(部分主机会禁用WP Cron,需联系主机开启或改用服务器Cron替代)。
内容的提问来源于stack exchange,提问作者shaik maboo basha
相关产品推荐
相关产品推荐

