Custom WooCommerce Order Status
December 24, 2024 · AI Conversations
### 1. Add the Custom Order Status
You can use the `register_post_status` function to register a new order status and then add it to the list of order statuses using WooCommerce hooks.
Here’s a code snippet to add a `dispensing` order status:
// Register custom order status 'dispensing'
add_action('init', function () {
register_post_status('wc-dispensing', array(
'label' => _x('Dispensing', 'Order status', 'your-text-domain'),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop('Dispensing (%s)', 'Dispensing (%s)', 'your-text-domain'),
));
});
// Add 'dispensing' to WooCommerce order statuses
add_filter('wc_order_statuses', function ($order_statuses) {
$new_statuses = [];
foreach ($order_statuses as $key => $status) {
$new_statuses[$key] = $status;
// Insert 'wc-dispensing' after 'wc-processing'
if ('wc-processing' === $key) {
$new_statuses['wc-dispensing'] = _x('Dispensing', 'Order status', 'your-text-domain');
}
}
return $new_statuses;
});
### 2. Set Order to the `dispensing` Status
You can programmatically change the order status to `dispensing` using:
$order = wc_get_order($order_id);
$order->update_status('wc-dispensing', __('Order is now being dispensed.', 'your-text-domain'));
### 3. Customize the Workflow (Optional)
You can integrate this status into automated workflows or trigger custom actions using the `woocommerce_order_status_changed` hook:
add_action('woocommerce_order_status_changed', function ($order_id, $old_status, $new_status) {
if ('dispensing' === $new_status) {
// Perform actions when the order status changes to 'dispensing'
error_log("Order #{$order_id} is now in the dispensing status.");
}
}, 10, 3);
### 4. Add Custom Email Notifications (Optional)
To notify customers or admins when the order status changes to `dispensing`, you can create a custom email class and hook it into WooCommerce's email system.
Would you like detailed steps on creating a custom email for this status?