WC_Form_Handler::cancel_order()public staticWC 1.0

Cancel a pending order.

Method of the class: WC_Form_Handler{}

Return

null. Nothing (null).

Usage

$result = WC_Form_Handler::cancel_order();

WC_Form_Handler::cancel_order() code WC 9.4.2

public static function cancel_order() {
	if (
		isset( $_GET['cancel_order'] ) &&
		isset( $_GET['order'] ) &&
		isset( $_GET['order_id'] ) &&
		( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), 'woocommerce-cancel_order' ) ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
	) {
		wc_nocache_headers();

		$order_key        = wp_unslash( $_GET['order'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$order_id         = absint( $_GET['order_id'] );
		$order            = wc_get_order( $order_id );
		$user_can_cancel  = current_user_can( 'cancel_order', $order_id );
		$order_can_cancel = $order->has_status( apply_filters( 'woocommerce_valid_order_statuses_for_cancel', array( 'pending', 'failed' ), $order ) );
		$redirect         = isset( $_GET['redirect'] ) ? wp_unslash( $_GET['redirect'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

		if ( $user_can_cancel && $order_can_cancel && $order->get_id() === $order_id && hash_equals( $order->get_order_key(), $order_key ) ) {

			// Cancel the order + restore stock.
			WC()->session->set( 'order_awaiting_payment', false );
			$order->update_status( 'cancelled', __( 'Order cancelled by customer.', 'woocommerce' ) );

			wc_add_notice( apply_filters( 'woocommerce_order_cancelled_notice', __( 'Your order was cancelled.', 'woocommerce' ) ), apply_filters( 'woocommerce_order_cancelled_notice_type', 'notice' ) );

			do_action( 'woocommerce_cancelled_order', $order->get_id() );

		} elseif ( $user_can_cancel && ! $order_can_cancel ) {
			wc_add_notice( __( 'Your order can no longer be cancelled. Please contact us if you need assistance.', 'woocommerce' ), 'error' );
		} else {
			wc_add_notice( __( 'Invalid order.', 'woocommerce' ), 'error' );
		}

		if ( $redirect ) {
			wp_safe_redirect( $redirect );
			exit;
		}
	}
}