Enhance the user experience on your WooCommerce store by allowing customers to easily cancel pending or processing orders directly from their account. In this tutorial, we’ll guide you through adding a “Cancel Order” button to the order details page in the customer’s account.
/**
* Snippet Name: Add Cancel Order Button to My Account Order Details Page
* Snippet Author: wpsnippets.dev
*/
// Add Cancel Order Button to My Account Order Details Page
function wps_add_cancel_order_button( $order ) {
$order_id = $order->get_id();
$order_status = $order->get_status();
// Check if the order status is pending or processing
if ( in_array( $order_status, array( 'pending', 'processing' ) ) ) {
echo '<form method="post"> // Output the cancel order button
<input type="hidden" name="cancel_order" value="' . $order_id . '">
<button type="submit" class="button cancel-order">Cancel Order</button>
</form>';
}
}
add_action( 'woocommerce_order_details_after_order_table', 'wps_add_cancel_order_button', 10 );
//Process Cancel Order Action
function wps_process_cancel_order_action() {
if ( isset( $_POST['cancel_order'] ) && is_user_logged_in() ) { // Check if the cancel order button is clicked
$order_id = absint( $_POST['cancel_order'] );
$order = wc_get_order( $order_id ); // Get the order object
// Check if the order exists and is associated with the current user
if ( $order && get_current_user_id() === $order->get_customer_id() ) {
$order->update_status( 'cancelled' ); // Cancel the order
wp_redirect( wc_get_account_endpoint_url( 'orders' ) ); // Redirect to the My Account Orders page
exit;
}
}
}
add_action( 'init', 'wps_process_cancel_order_action' );
Code Explanation
- We use the woocommerce_order_details_after_order_table hook to add the cancel order button below the order details table.
- The button is displayed only if the order status is pending or processing.
- When the button is clicked, the process_cancel_order_action function is triggered.
- This function cancels the order and redirects the user back to their My Account Orders page.