Search code examples
phpwordpresswoocommerceordersemail-notifications

Get customer order count in new order email notification


I'd like to indicate in WooCommerce "new order" email notification, if it's a repeat customer.

It seems simple, but I've tried about 5 different methods and none worked. I've tried putting this into 2 different hooks:

  • woocommerce_email_after_order_table
  • woocommerce_email_subject_new_order.

Seems like wc_get_customer_order_count($user->ID) should work but it appears that the $user object is not passed into those hook's functions, right?

I'm also wondering if this is possible when it's a guest and not a registered user, maybe by comparing the email address?

Thanks


Solution

  • WooCommerce Email notifications are related to orders.

    In woocommerce_email_after_order_table hook, you have the Order object as an argument in your hooked custom function and also the $email object.

    With that $order object, you can get the user ID this way:

    $user_id = $user_id = $order->get_user_id();
    

    From the $email object you can target the new order email notification.

    So the working code is going to be:

    add_action( 'woocommerce_email_after_order_table', 'customer_order_count', 10, 4);
    function customer_order_count( $order, $sent_to_admin, $plain_text, $email ){
    
        if ( $order->get_user_id() > 0 ){
    
            // Targetting new orders (that will be sent to customer and to shop manager)
            if ( 'new_order' == $email->id ){
    
                // Getting the user ID
                $user_id = $order->get_user_id();
    
                // Get the user order count
                $order_count = wc_get_customer_order_count( $user_id );
    
                // Display the user order count
                echo '<p>Customer order count: '.$order_count.'</p>';
    
            }
        }
    }
    

    You can also use instead the woocommerce_email_before_order_table hook for example…

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

    This code is tested and works.