CRyan
CRyan

Reputation: 23

WooCommerce Bookings - Change Order status from "Pending Payment" to "Cancelled" after 24 hours

I have am using WooCommerce Bookings where customers can request a booking that needs to be confirmed by the Admin. If the Admin does not confirm the booking I would like the order to be automatically cancelled after 24 hours.

From Change WooCommerce order status after X time has passed answer code, I am looking for any assistance to meet my requirement, using WP cron.

Upvotes: 1

Views: 1146

Answers (1)

CRyan
CRyan

Reputation: 23

I am returning with a working solution to my requirement. I hope it helps someone.

An event is scheduled to run every 30 minutes checking for pending orders older than 24 hours and cancels them.

/**
 * Create custom scheduled hook
 *
 * @param $schedules
 * @return mixed
 */
function custom_cron_schedule( $schedules ) {
    if ( ! isset( $schedules["30min"] ) ) {
        $schedules["30min"] = array(
            'interval' => 30 * 60,
            'display' => __( 'Once every 30 minutes' )
        );
    }
    return $schedules;
}
add_filter( 'cron_schedules','custom_cron_schedule' );

//Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'custom_pending_orders_hook' ) ) {
    wp_schedule_event( time(), '30min', 'custom_pending_orders_hook' );
}

add_action( 'custom_pending_orders_hook', 'custom_cancel_pending_orders' );

/**
 * Function to run on the scheduled event, checking for orders older than 24 hours
 *
 */
function custom_cancel_pending_orders() {
    // Get bookings older than 24 hours and with pending status
    $args = array(
        'post_type' => 'wc_booking',
        'posts_per_page' => -1,
        'post_status' => 'pending-confirmation',
        'date_query' => array(
            array(
                'before' => '24 hours ago' // hours ago
            )
        )
    );

    // do the query
    $query = new \WP_Query( $args );

    // The Loop
    if ( $query->have_posts() ) {
        // Get the posts
        $bookings = $query->posts;

        // Loop through posts
        foreach ( $bookings as $booking ) {
            if ( class_exists('WC_Booking') ) {
                // Get the booking object using the id of the post
                $wc_booking = new \WC_Booking( $booking->ID );

                // Change the status
                if ( $wc_booking ) {
                    $wc_booking->update_status( 'cancelled' );
                }
            }
        }
    } else {
        // no posts found, moving on
    }

    // Restore original Post Data
    wp_reset_postdata();
}

Upvotes: 1

Related Questions