I am using the following code to change the status of an order in a woocommerce site when a given field 'ship_by_date_dont_edit' is within 2 (or less) days of today's date (via cron job). Everything works great, but I also need to account for negative days, as sometimes we will get a last-minute rush order, and the "ship by date" will get set as a date in the past. Upon testing, it does not seem days of less than 0 are included, thus the status does not change for those orders. I'm hoping to get some help so that my function works for dates within 2 days (or less, negative included).
Below is the original (messy) code:
//==== status change to 'preparing to ship'
add_action( 'new_cron_status_update_lessthan_two_days', 'wp_order_status_update', 10, 1 );
function wp_order_status_update() {
global $wpdb;
$my_query = "SELECT * FROM wp_wc_order_stats where STATUS='wc-processing'";
$result2 = $wpdb->get_results($my_query);
foreach ($result2 as $results2) {
$order_id = $results2->order_id;
$thisacof7 = get_post_meta( $order_id, 'ship_by_date_dont_edit', true );
$date1=$thisacof7; // date("Y-m-d h:i:s");
$thisdate=date("Y-m-d h:i:s");
$dateStart = new DateTime($date1);
$datetoday = new DateTime($thisdate);
$dteDiff = $dateStart->diff($datetoday);
$Diff = $dteDiff->format("%a");
if($Diff<2) {
$order = new WC_Order($order_id);
if (!empty($order)) {
$order->update_status( 'wc-preparing-to-ship' );
}
}
}
}
I tried adding a "$Diff->invert;" variable and using an else function to test if the result is a 1 (shouldn't this indicate a negative number?), but it then made all my orders change, even those with dates more than 60 days into the future, so I clearly did something wrong there.
$resultPos = $Diff->invert;
elseif ($resultPos=1) {
$order = new WC_Order($order_id);
if (!empty($order)) {
$order->update_status( 'wc-preparing-to-ship' );
}
}