Search code examples
phpwordpresswoocommerceordersemail-notifications

Add shipping state to subject in WooCommerce new order email notification


I've already succeeded in finding a way to change the subject of the WooCommerce new order email notification. The problem I'm facing is that the object $order doesn't process the shipping_state of the user profile.

Here is the code:

add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 1, 2);

function change_admin_email_subject( $subject, $order ) {
    global $woocommerce;

    $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

    $subject = sprintf( 'Commande pour  %s', $order->shipping_state);

    return $subject;
}

I tried calling it directly from the user metadata, but it doesn't work, where it should appear the data, it appears blank.

Here is the code I tried:

function change_admin_email_subject( $subject, $user) {
    global $woocommerce;

    $user = wp_get_current_user();  $current_user_id = 
    $user -> ID;

    $user_billing_state = get_user_meta($current_user_id, 'shipping_state', true); 

    $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

    $subject = sprintf( 'Commande pour  %s', 
    $user_billing_state);

    return $subject;
}

Any advice would be appreciated.


Solution

  • Your code attempt(s) contain some mistakes:

    • $order->shipping_state is no longer applicable since WooCommerce 3 and has been replaced by $order->get_shipping_state()
    • The use of global $woocommerce; is not necessary
    • You use $blogname, but you don't do anything with this data, for example you don't display it in the subject

    So you get:

    function filter_woocommerce_email_subject_new_order( $subject, $order ) {
        // Get shipping state
        $shipping_state = $order->get_shipping_state();
        
        // NOT empty
        if ( ! empty( $shipping_state ) ) {
            // Get blogname
            $blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
        
            // Change subject
            $subject = sprintf( __( '%s: Commande pour %s', 'woocommerce' ), $blogname, $shipping_state );
        }
    
        return $subject;
    }
    add_filter( 'woocommerce_email_subject_new_order', 'filter_woocommerce_email_subject_new_order', 10, 2 );