WooCommerce修改订单修改日期失败求助(v7.9.0)
解决WooCommerce订单修改日期总是被设为当前时间的问题
你遇到的问题是因为WooCommerce在调用save()方法时,会自动把订单的修改日期重置为当前时间,直接用set_date_modified()后保存会被这个默认行为覆盖。下面给你两种可行的解决方法:
方法一:直接更新订单元数据
绕过WooCommerce的自动更新逻辑,直接修改存储修改日期的元字段(需要同时更新本地时间和GMT时间两个字段):
$order = wc_get_order(5029); $now = new DateTime(); $now->modify('-4 day'); // 更新本地时间的修改日期元数据 $order->update_meta_data('_date_modified', $now->format('Y-m-d H:i:s')); // 更新GMT时间的修改日期元数据(先转UTC时区) $utc_now = clone $now; $utc_now->setTimezone(new DateTimeZone('UTC')); $order->update_meta_data('_date_modified_gmt', $utc_now->format('Y-m-d H:i:s')); $order->save();
方法二:临时移除自动更新钩子
在保存订单前,临时移除WooCommerce自动更新修改日期的钩子,保存后再恢复:
$order = wc_get_order(5029); $now = new DateTime(); $now->modify('-4 day'); // 获取订单数据存储实例,移除自动更新修改日期的钩子 $order_store = WC_Data_Store::load('order'); remove_action('woocommerce_before_object_save', array($order_store, 'update_date_modified')); // 设置修改日期并保存 $order->set_date_modified($now->getTimestamp()); $order->save(); // 恢复钩子,避免影响后续其他订单操作 add_action('woocommerce_before_object_save', array($order_store, 'update_date_modified'));
这两种方法都能让你成功把订单5029的修改日期设置为4天前的时间,根据你的习惯选一种就行。
内容的提问来源于stack exchange,提问作者ebeliejinfren
相关产品推荐
相关产品推荐

