Get customer order count in new order email notification

半城伤御伤魂 提交于 2019-12-22 17:51:28

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/42125823/get-customer-order-count-in-new-order-email-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!