Reputation: 11
I'm looking for a solution to add Custom Meta to each order in WooCommerce based on the shipping method chosen at the checkout. As far as I can see there have been some updates since WooCommerce 3.0 so I'm struggling to find a definitive answer to this.
Here's what I have so far.
According to this thread the WC3+ / CRUD method would be:
add_action('woocommerce_checkout_create_order', 'before_checkout_create_order', 20, 2);
function before_checkout_create_order( $order, $data ) {
$order->update_meta_data( '_custom_meta_key', 'value' );
}
And according to this thread, you can use the shipping method conditionally using:
// Conditional function based on the Order shipping method
if( $order->has_shipping_method('flat_rate') ) {
The problem I am having is combining these functions. Here's what I have tried but it doesn't seem to work:
add_action('woocommerce_checkout_create_order', 'before_checkout_create_order', 20, 2);
function before_checkout_create_order( $order, $data ) {
if( $order->has_shipping_method('Special Delivery') ) {
$order->update_meta_data( 'royal_mail_shipping_code', 'SD1' );
}
if( $order->has_shipping_method('Royal Mail Tracked 48') ) {
$order->update_meta_data( 'royal_mail_shipping_code', 'TPS' );
}
}
Any help getting the above code working would be hugely appreciated!
Upvotes: 1
Views: 1977
Reputation: 21
Try this:
add_action('woocommerce_checkout_update_order_meta',function( $order_id, $posted ) {
if( $order->has_shipping_method('Special Delivery') ) {
$order = wc_get_order( $order_id );
$order->update_meta_data( 'royal_mail_shipping_code', 'SD1' );
$order->save();
}
if( $order->has_shipping_method('Royal Mail Tracked 48') ) {
$order = wc_get_order( $order_id );
$order->update_meta_data( 'royal_mail_shipping_code', 'TPS' );
$order->save();
}
} , 10, 2);
Upvotes: 1