以编程方式更新 Woocommerce 订单上的修改日期

Update programmatically date modified on Woocommerce Orders

我正在获取挂单列表,抓取一些数据并计算 post 上次编辑是否在 2 周内。如果不是我正在做一些事情然后尝试将修改日期设置为今天,update_post_meta 不起作用,它什么都不做。我在顶部声明的所有变量都有效,我正在进入 if 语句。

    $customer_orders = wc_get_orders(array(
        'limit'    => -1,
        'status'   => array('wc-pending')
    ) );

    foreach($customer_orders as $order) {

        $orderData = $order->get_data();
        $orderId = $orderData['id'];
        $orderDate = $orderData['date_modified']->date('Y-m-d H:i:s');
        $orderDatePlus2Weeks = new DateTime($orderDate);
        $orderDatePlus2Weeks->add(new DateInterval('P14D'));
        $orderDatePlus2Weeks = $orderDatePlus2Weeks->format('Y-m-d H:i:s');
        $today = date("Y-m-d H:i:s");

        if($orderDatePlus2Weeks <= $today){
            echo 'THIS ORDER NEEDS UPDATED';
            // Do Some Stuff
            update_post_meta($orderId, 'date_modified', $today);
        }else{
            echo 'THIS ORDER DOES NOT NEED UPDATED';
        }
    }

从 Woocommerce 3 和 CRUD objects 开始,您可以使用 WC_Order getter 和 setter 方法。试试这个:

$customer_orders = wc_get_orders(array(
    'limit'    => -1,
    'status'   => array('wc-pending')
) );

foreach($customer_orders as $order) {
    $order_id = $order->get_id();

    $date_modified = $order->get_date_modified();
    $time_zone = $date_modified->getTimezone();

    $date_modified_p14d = new DateTime($date_modified);
    $date_modified_p14d->add(new DateInterval('P14D'));

    $now = new DateTime();
    $now->setTimezone($time_zone);

    if( $date_modified_p14d->getTimestamp() <= $now->getTimestamp() ){
        echo 'THIS ORDER NEEDS UPDATED';
        // Do Some Stuff
        $order->set_date_modified($now->getTimestamp());
        $order->save();
    }else{
        echo 'THIS ORDER DOES NOT NEED UPDATED';
    }
}

已测试并有效。