Search code examples
woocommerce-subscriptions

How to send customer renewal order to secondary email in Woocommerce subscription


I want to send the renewal order email to a secondary user email(which i have added in user-edit page using ACF).

I have tried many methods,woocommerce_subscription_payment_complete is also not working for me.

The following code i have tried:

   add_action( 'woocommerce_order_status_completed', 'action_on_order_status_completed', 20, 2 );


 function action_on_order_status_completed( $order_id, $order ){

    $order = new WC_Order($order_id);

    // Get the user ID from WC_Order methods
    $user_id = $order->get_user_id(); // or $order->get_customer_id();

    $secondary_recipient = get_field('secondary_email', 'user_'.$user_id );

            $subscriptions_ids = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) );
    // We get all related subscriptions for this order

    foreach( $subscriptions_ids as $subscription_id => $subscription_obj )
        if($subscription_obj->order->id == $order_id) break; // Stop the loop

        // $subscription_objc = wcs_get_subscription($subscription_id);
        //$userid = $subscription_objc->get_user_id();

    $wc_emails = WC()->mailer()->get_emails();
    $wc_emails['WCS_Email_Processing_Renewal_Order']->recipient =  $secondary_recipient;
    $wc_emails['WCS_Email_Processing_Renewal_Order']->trigger($subscription_id);

    // $to = $secondary_recipient;
    //  $subject = "hi";
    //  $body =$user_id."end".$order_id."hhh".$subscription_id;
        
    //  $headers = array('Content-Type: text/html; charset=UTF-8');
    //  //$headers[] = 'Cc: [email protected]';
    //  wp_mail( $to, $subject, $body, $headers );

   }

FYI:Email is sending if i use the commented wp_mail function.


Solution

  • We can add a secondary email as the recipient, Try the below code tested and it worked.

    add_filter( 'woocommerce_email_recipient_customer_completed_renewal_order', 'my_email_recipient_filter_function', 10, 2);
    
    function my_email_recipient_filter_function( $recipient, $order ) {
    $user_id = $order->get_user_id(); // or $order->get_customer_id();
    $secondary_recipient = get_field('secondary_email', 'user_'.$user_id ); 
    if(! empty($secondary_recipient)){
    $recipient = $recipient   . ', '. $secondary_recipient;
    return $recipient;
    }else {
    return $recipient;    
    }
    }