3
votes

I am using WooCommerce Subscriptions. I've customized the cancelled-subscription template and it works when a customer cancels a subscription, sending the custom email to the admin but I'm unable to get it to send the cancellation email to the customer.

I've tried adapting code found on stackoverflow

/* Send email to customer on cancelled order in WooCommerce */
add_action('woocommerce_subscription_status_updated', 'send_custom_email_notifications', 10, 3 );
function send_custom_email_notifications( $subscription, $new_status, $old_status ){
    if ( $new_status == 'cancelled' || $new_status == 'pending-cancel' ){
        $wc_emails = WC()->mailer()->get_emails(); // Get all WC_emails objects instances

        $customer_email = $subscription->get_billing_email(); // The customer email

        $wc_emails['WC_Email_Cancelled_Order']->recipient .= ',' . $customer_email;
        $wc_emails['WC_Email_Cancelled_Order']->trigger( $subscription->id );
    } 
}

but neither admin or customer gets the email.

EDIT 1

I'm finally able to send the Subscription Cancellation Email to both Admin and the Customer with this updated code

/* Send email to customer on cancelled order in WooCommerce */
add_action('woocommerce_subscription_status_updated', 'send_custom_email_notifications', 10, 3 );
function send_custom_email_notifications( $subscription, $new_status, $old_status ){
    if ( $new_status == 'cancelled' || $new_status == 'pending-cancel' ){
        $customer_email = $subscription->get_billing_email();
        $userid = $subscription->get_user_id();
        $wc_emails = WC()->mailer()->get_emails();
        $wc_emails['WC_Email_Cancelled_Order']->recipient .= ',' . $customer_email;
        $wc_emails['WC_Email_Cancelled_Order']->trigger( $orderid );
    } 
}
1

1 Answers

1
votes

Thank you for sharing your recipie. I've had the same goal - to send an email to customer with a subscription cancellation confirmation.

I did some updates to your solution and ended up with the following.

  1. We can install hook on certain subscription status changes, so we avoid status checks inside a function
/* Send email to a customer on cancelled subscription in WooCommerce */
add_action( 'woocommerce_subscription_status_pending-cancel', 'sendCustomerCancellationEmail' );
  1. We can use WCS_Email_Cancelled_Subscription class to trigger corresponding email. Trigger function requires a subscription object in that case.
/**
 * @param WC_Subscription $subscription
 */
function sendCustomerCancellationEmail( $subscription ) {
    $customer_email = $subscription->get_billing_email();
    $wc_emails = WC()->mailer()->get_emails();
    $wc_emails['WCS_Email_Cancelled_Subscription']->recipient = $customer_email;
    $wc_emails['WCS_Email_Cancelled_Subscription']->trigger( $subscription );
}