Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

php - Custom subject for New Order Email notification in WooCommerce

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...