简体   繁体   中英

How to add Custom Meta Data to a WooCommerce Order based on the Shipping Method

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM