WooCommerce预订-24小时后将订单状态从“待付款”更改为“已取消”

时间:2020-06-24 18:50:19

标签: php wordpress woocommerce woocommerce-bookings

我正在使用WooCommerce预订,客户可以在其中请求需要管理员确认的预订。如果管理员未确认预订,我希望订单在24小时后自动取消。

Change WooCommerce order status after X time has passed 答案代码中,我正在寻找可使用WP cron满足我要求的任何帮助。

1 个答案:

答案 0 :(得分:0)

我将根据我的要求提供可行的解决方案。我希望它可以帮助某人。

按计划每30分钟运行一次活动,以检查24小时之前的待处理订单并取消订单。

 * 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();
}