Last active
July 15, 2020 21:06
-
-
Save vanbo/4659f5cdf3842a56c80b786c4fc9c5f7 to your computer and use it in GitHub Desktop.
WooCommerce Cancel Failed Payment Orders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Cancel all failed orders after held duration | |
| * The method is adapted from the WooCommerce "wc_cancel_unpaid_orders" function and uses 'woocommerce_cancel_unpaid_orders' schedule hook | |
| * | |
| * Code location: Add the code to your "child-theme/functions.php" file | |
| * | |
| * Requirements: "Product > Inventory > Manage Stock" enabled, and time set in the "Product > Inventory > Hold stock (minutes)" setting. | |
| */ | |
| function vanbo_cancel_failed_orders() { | |
| $held_duration = get_option( 'woocommerce_hold_stock_minutes' ); | |
| if ( $held_duration < 1 || 'yes' !== get_option( 'woocommerce_manage_stock' ) ) { | |
| return; | |
| } | |
| $date = strtotime( '-' . absint( $held_duration ) . ' MINUTES', current_time( 'timestamp' ) ); | |
| global $wpdb; | |
| $unpaid_orders = $wpdb->get_col( | |
| $wpdb->prepare( | |
| // @codingStandardsIgnoreStart | |
| "SELECT posts.ID | |
| FROM {$wpdb->posts} AS posts | |
| WHERE posts.post_type IN ('" . implode( "','", wc_get_order_types() ) . "') | |
| AND posts.post_status = 'wc-failed' | |
| AND posts.post_modified < %s", | |
| // @codingStandardsIgnoreEnd | |
| gmdate( 'Y-m-d H:i:s', absint( $date ) ) | |
| ) | |
| ); | |
| if ( $unpaid_orders ) { | |
| foreach ( $unpaid_orders as $unpaid_order ) { | |
| $order = wc_get_order( $unpaid_order ); | |
| $order->update_status( 'cancelled', __( 'Failed payment order cancelled - time limit reached.', 'woocommerce' ) ); | |
| } | |
| } | |
| } | |
| add_action( 'woocommerce_cancel_unpaid_orders', 'vanbo_cancel_failed_orders', 9 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment