Home > Back-end >  Change sender name to value from order meta data in WooCommerce email notifications
Change sender name to value from order meta data in WooCommerce email notifications

Time:11-13

I'm trying to change WooCommerce sender email name based on the order meta.

The website is a multi vendor marketplace, so each order contains meta data with the business name to which the customer orders. So when the order status changes to processing, what I am trying to do is get the business name from the order meta, and set the sender email name to that meta. This way, the customer will see the business name in the email he receives when placing an order.

This is what I've tried, but unfortunately without the desired result. Any advice?

function change_processing_sender_name($order_id){
    $merchant_id = get_post_meta( $order_id, 'merchant_id', true );
    $business_name = get_user_meta($merchant_id,'businessname', true);
    add_filter( 'woocommerce_email_from_name', function( $from_name, $wc_email ){
        $from_name = $business_name;
        return $from_name;
    }, 10 ,2);
}
add_action( 'woocommerce_order_status_processing', 'change_processing_sender_name' );

CodePudding user response:

It is not necessary to add this filter in the woocommerce_order_status_processing hook, when the order status changes to processing. Because we can apply the reverse. Via $email->id it is possible to target specific email notifications when this hook is triggered.

To obtain meta data belonging to the order, you can use $order->get_meta( 'meta_key' )

So you get:

function filter_woocommerce_email_from_name( $from_name, $email ) {
    // Targeting specific email notification via the email id
    if ( $email->id == 'customer_processing_order' && is_a( $email->object, 'WC_Order' ) ) {
        // Get order
        $order = $email->object;
        
        // Get meta
        $business_name = $order->get_meta( 'businessname' );

        // NOT empty
        if ( ! empty ( $business_name  ) ) {
            $from_name = $business_name;
        }
    }

    return $from_name;
}
add_filter( 'woocommerce_email_from_name', 'filter_woocommerce_email_from_name', 10, 2 );
  • Related