3
votes

In WooCommerce I would like to set the product purchased in the "new order" email subject line, something like this: New Order - [{product_name}] ({order_number}) - {order_date}

I understand that product_name cant be used probably due to multiple products is there a way I can still do this by filtering product ordered or just allowing multiple products as not many multi orders go through.

I am very new to modifying theme code.

1

1 Answers

2
votes

The Email settings for "New Order" the subject need to be (as in your question):

New Order - [{product_name}] ({order_number}) - {order_date}

In the code below I replace {product_name} by the items product names (separated by a dash) as an order can have many items…

This custom function hooked in woocommerce_email_subject_new_order will do the trick:

add_filter( 'woocommerce_email_subject_new_order', 'customizing_new_order_subject', 10, 2 );
function customizing_new_order_subject( $formated_subject, $order ){
    // Get an instance of the WC_Email_New_Order object
    $email = WC()->mailer->get_emails()['WC_Email_New_Order'];
    // Get unformatted subject from settings
    $subject = $email->get_option( 'subject', $email->get_default_subject() );
    
    // Loop through order line items
    $product_names = array();
    foreach( $order->get_items() as $item )
        $product_names[] = $item->get_name(); // Set product names in an array
    
    // Set product names in a string with separators (when more than one item)
    $product_names = implode( ' - ', $product_names );
    
    // Replace "{product_name}" by the product name
    $subject = str_replace( '{product_name}', $product_names, $subject );

    // format and return the custom formatted subject
    return $email->format_string( $subject );
}

Code goes in function.php file of your active child theme (or active theme).

Tested and works.


You will get something like this:

enter image description here