I have created a PHP function that calculates how old a WordPress/WooCommerce order is. If the order is older than 90 days it should be canceled. The function used to work perfectly. However, since the new year 2020, it has stopped working. I would assume it’s because the function gets confused about the year since -90 days from today is year 2019. How can I make the calculation work with the past years/2019?
I have tried playing with different date formats from the WordPress codex instead of mdy. However, this doesn’t seem to do any difference.
function expire_after_x_days(){ global $wpdb; // Get current time $today = date("m/d/y"); // set time to expire $time_to_expire = "-90 days"; $expiration_date = date("m/d/y", strtotime( $today . $time_to_expire)); // Get orders with processing status $result = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'shop_order' AND post_status = 'wc-processing'"); if( !empty($result)) foreach ($result as $order){ // Get order's time $order_time = get_the_time('m/d/y', $order->ID ); // Compare order's time with current time if ( $order_time < $expiration_date ){ // Update order status $orders = array(); $orders['ID'] = $order->ID; $orders['post_status'] = 'wc-cancelled'; wp_update_post( $orders ); } } } add_action( 'admin_footer', 'expire_after_x_days' );
Advertisement
Answer
You can simplify this a lot by running an UPDATE
query with a WHERE
clause, to only fetch those orders that are older than 90 days. No need to fetch them all and loop over the results.
You will need to set the post_created
to the actual name of your column.
function expire_after_x_days() { global $wpdb; $result = $wpdb->query("UPDATE $wpdb->posts SET post_status = 'wc-cancelled' WHERE post_type = 'shop_order' AND post_status = 'wc-processing' AND post_created < DATE_SUB(NOW(), INTERVAL 90 DAY)"); }