Search code examples
wordpresswoocommercehook-woocommerceordersemail-notifications

Which hook to use to save order meta data before email notifications are send in WooCommerce


I'm looking for a Woocommerce action hook (or filter, I'm not sure) where I can update the shipping & billing address before the New Order email notification is sent.

Right now, I'm using the woocommerce_before_thankyou to update order meta.

The order is saved with correct address that I want to save, but the email is not displaying the correct address.

Here is the example code, similar with what I'm doing:

add_action( 'woocommerce_thankyou', 'checkout_save_user_meta');

function checkout_save_user_meta( $order_id ) {
    $order = wc_get_order( $order_id );
    $my_custom_address = 'My custom address';
    
    update_post_meta( $order_id, '_billing_address_1',  $my_custom_address );
    update_post_meta( $order_id, '_shipping_address_1',  $my_custom_address );
}

Any advice on which hook to use for this case?


Solution

  • You can use the woocommerce_checkout_create_order or the woocommerce_checkout_update_order_meta action hook.

    So you would get:

    /**
     * Action hook to adjust order before save.
     *
     * @since 3.0.0
     */
    function action_woocommerce_checkout_create_order( $order, $data ) {    
        // Some value
        $my_custom_address = 'My custom address';
    
        // Update meta data
        $order->update_meta_data( '_billing_address_1', $my_custom_address );
        $order->update_meta_data( '_shipping_address_1', $my_custom_address );
    }
    add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );
    

    OR

    /**
     * Action hook fired after an order is created used to add custom meta to the order.
     *
     * @since 3.0.0
     */
    function action_woocommerce_checkout_update_order_meta( $order_id, $data ) {    
        // Get an instance of the WC_Order object
        $order = wc_get_order( $order_id );
        
        // Is a WC_Order
        if ( is_a( $order, 'WC_Order' ) ) {     
            // Some value
            $my_custom_address = 'My custom address';
    
            // Update meta data
            $order->update_meta_data( '_billing_address_1', $my_custom_address );
            $order->update_meta_data( '_shipping_address_1', $my_custom_address );
    
            // Save
            $order->save();
        }
    }   
    add_action( 'woocommerce_checkout_update_order_meta', 'action_woocommerce_checkout_update_order_meta', 10, 2 );