Celebrate CodingBunny’s founder turning 45 - 45% OFF
The offer will end in
DAYS
HOURS
MINUTES
Adds a cancel button for orders in specific statuses within a defined duration.
/**
* Snippet Name: Add Cancel Button for Specific Order Statuses
* Snippet Author: coding-bunny.com
* Description: Adds a cancel button for orders in specific statuses within a defined duration.
*/
// Hook into WooCommerce to validate order statuses for cancellation
add_filter( 'woocommerce_valid_order_statuses_for_cancel', 'cb_add_cancel_button', 20, 2 );
/**
* Function to add specific order statuses for cancellation
*
* @param array $statuses Existing valid order statuses.
* @param WC_Order|string $order The order object or order ID.
* @return array Modified array of valid order statuses.
*/
function cb_add_cancel_button( $statuses, $order = '' ) {
// Define the custom order statuses where the cancel button should appear
$custom_statuses = array( 'pending', 'processing', 'on-hold', 'failed' );
// Set the duration (3 hours) for which the cancel button will be available
$duration = 3 * 60 * 60; // 3 hours in seconds
// Retrieve the order object if not already passed
if ( ! is_object( $order ) && isset( $_GET['order_id'] ) ) {
$order = wc_get_order( absint( $_GET['order_id'] ) );
}
// Get the order creation and modification timestamps
$date_created_time = strtotime( $order->get_date_created() );
$now = strtotime( "now" );
// Check if the order is within the allowed cancellation duration
if ( ( $date_created_time + $duration ) >= $now ) {
return $custom_statuses;
} else {
return $statuses;
}
}.woocommerce-button.button.cancel {
background-color: #000000; /* Set the button background color here */
}
.woocommerce-button.button.cancel:hover {
background-color: #474747; /* Set the button background color on hover here */
}
.woocommerce-button.button.cancel::after {
content: '\00a0order'; /* Adds " ordine" to the button text */
}