The ‘Edit Order’ page can be modified; more specifically, the ‘Order actions’ metabox can have custom actions added to it.
Recently, I needed to add the ‘Cancel Order’ function to this list of ‘Order actions’ in the metabox.
It’s always handy, to further your understanding of the internals, to have some official WordPress & WooCommerce code references handy during development:
- The WordPress Function Reference @ codex.wordpress.org
- The WordPress Developer Documentation @ codex.wordpress.org
- The WordPress Developer Resources
- The WooCommerce Code Reference
Adding to the list of ‘Order actions’, we’re going to be working with methods & properties of the WooCommerce Order class:
The following web pages provide guidance about how to add to the list of ‘Order actions’:
- https://neversettle.it/add-custom-order-action-woocommerce/
- https://www.skyverge.com/blog/hook-into-woocommerce-actions/
- https://gist.github.com/jgarciaruiz/c4ad468ee89ab077332d1845b5c78457
My understanding of the code is that there are essentially two main objectives, represented below in two functions: 1) the custom action is added to the drop-down list of ‘Order actions’, and 2) the custom action is defined.
My resulting code follows below, as a modified version which originated at the github link above:
function my_wc_add_order_meta_box_action( $actions ) { global $theorder; // bail if the order has already been cancelled if ( $theorder->get_status() == 'cancelled' ) { return $actions; } // add "cancel" custom action to dropdown list $actions['wc_custom_order_action'] = __( 'Cancel' ); return $actions; } add_action( 'woocommerce_order_actions', 'my_wc_add_order_meta_box_action', 10, 1 ); function my_wc_custom_order_action ( $order ) { $order->update_status( 'cancelled', __( 'Order cancelled by Me.', 'woocommerce' ) ); } add_action( 'woocommerce_order_action_wc_custom_order_action', 'my_wc_custom_order_action' );
And that’s it! Now, in WooCommerce, you can cancel the order from the ‘Edit Order’ page.
No Comments Yet