Search code examples
phpwordpresswoocommercehook-woocommercewoocommerce-subscriptions

How can I send custom email when user order a subscription in Wordpress?


I would like to know if there is some way to send a custom email to a user when he makes a (first) payment in Woocommerce. (I am using Woocommerce Subscriptions).

This email is about instructions to learn how to set up an account on the website. So I think, maybe there's a problem. If the email is sent to an user each time there's a payment, then, when the subscription is renewed, I think they are going to receive the same email of the instructions.

The intention is this email with the instructions would only be sent to users for the first payment.

Thanks in advance!


Solution

  • we can send a custom mail for first time. you can use

    • woocommerce_order_status_processing
    • woocommerce_order_status_completed

    when user complete subscription, your order shows as processing we can use woocommerce_order_status_processing hook or is it shows as completed we can use woocommerce_order_status_completed hook. you can change order status in woocommerce subscription plugin

    //code goes to function.php you can generate child theme and cop
    
    add_action( 'woocommerce_order_status_completed', 'nazcloak_order_complete_actions', 10, 1);
    
    function nazcloak_order_complete_actions($order_id)
    {
        $order = wc_get_order( $order_id );
        $user_id = $order->get_user_id();
        $args = array(
            'customer_id' => $user_id,
            'limit' => 2, // if you set -1 it'll retrive all orders
        );
        $orders = wc_get_orders($args);
        if( !empty($orders) && count($orders) < 2 )
        {
            $to = $order->get_billing_email(); //to get user email
            $first_name = $order->get_billing_first_name();
            $subject = 'Thank You for Subscription!';
            $message = "Hello $first_name, your message.";
    
            wp_mail( $to, $subject, $message ); //send email using
        }
    }
    

    to change from email

    add_filter("wp_mail_from",  function($from){
     return "[email protected]";
    });