1

I'm using the woocommerce_payment_complete() function to send a custom email with order details after a payment has been completed:

add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
    $order      = wc_get_order( $order_id );
    $first_name = $order->get_billing_first_name();
    $last_name      = $order->get_billing_last_name();
    $company        = $order->get_billing_company();
    $email          = $order->get_billing_email();
    $order_number   = $order->get_order_number();
    $items      = $order->get_items();
    $total      = $order->get_total();
    $more_info      = $order->get_customer_note();

    foreach ($items as $item) {
        $product_name   = $item->get_name();
    }

    $to = $email;
    $subject = 'Order Details';
    $body = 'This order total is: ' . $total . '<br />First name: ' . $first_name . '<br />Last name: ' . $last_name . '<br />Company: ' . $company . '<br />Email: ' . $email . '<br />Order number: ' . $order_number . '<br />Items: ' . $product_name;
    $headers = array('Content-Type: text/html; charset=UTF-8');

    wp_mail( $to, $subject, $body, $headers );

    return $order_id;
}

It works, except for one thing. The problem is that the 'Items' ($product_name) part of the email notification only shows something if there was only one product in the order. If there is more than one product, the 'Items' show nothing.

What am I doing wrong?

User_FTW
  • 504
  • 1
  • 16
  • 44

1 Answers1

1

The problem is in the foreach loop, with each loop you are going to overwrite the current variable (product name) with the product name of the next product.

Example:

$items = array("foo", "bar", "hello", "world");

foreach ($items as $item) {
    $product_name = $item;
}

// Result = world
echo $product_name;

The solution for this is to concatenate the string

so instead of $variable = something;

Use $variable .= something;

So you get

Example:

$items = array("foo", "bar", "hello", "world");

$product_name = '';

foreach ($items as $item) {
    // The product name
    $product_name .= $item . ' - ';
}

// Result = foo - bar - hello - world -
echo $product_name;

Solution: replace your current foreach loop with the following code

$product_name = '';

foreach ($items as $item) {
    // The product name
    $product_name .= $item->get_name() . ' - ';
}
7uc1f3r
  • 28,449
  • 17
  • 32
  • 50