Add a custom Metabox to WooCommerce admin orders with HPOS enabled
use Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;
add_action( 'add_meta_boxes', 'admin_order_custom_metabox' );
function admin_order_custom_metabox() {
$screen = class_exists( '\Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController' ) && wc_get_container()->get( CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled()
? wc_get_page_screen_id( 'shop-order' )
: 'shop_order';
add_meta_box(
'custom',
'Custom Meta Box',
'custom_metabox_content',
$screen,
'side',
'high'
);
}
function custom_metabox_content( $object ) {
$order = is_a( $object, 'WP_Post' ) ? wc_get_order( $object->ID ) : $object;
echo '<p>Number (ID): '.$order->get_order_number().'<p>';
echo '<a>Test button</a>';
}
function custom_metabox_content( $object ) {
$order = is_a( $object, 'WP_Post' ) ? wc_get_order( $object->ID ) : $object;
echo '<p>
<label for="number_id">' . __('Number ID') . ':<label><br>
<input type="text" id="number_id" class="number_id" name="number_id" value="' . $order->get_meta('number_id') . '" />
<p>';
}
add_action( 'woocommerce_process_shop_order_meta', 'save_number_id_value', 20 );
function save_number_id_value( $order_id ) {
$order = wc_get_order( $order_id );
if ( isset($_POST['number_id']) ) {
$order->update_meta_data('number_id', sanitize_text_field($_POST['number_id']));
$order->save();
}
}