首页 > 解决方案 > 获取所有 WooCommerce 订单项目以在变量中使用

问题描述

我正在使用 woocommerce_payment_complete() 函数在付款完成后发送包含订单详细信息的自定义电子邮件:

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;
}

它有效,除了一件事。问题是电子邮件通知的“项目”($product_name) 部分仅在订单中只有一个产品时才会显示某些内容。如果有多个产品,则“项目”不显示任何内容。

我究竟做错了什么?

标签: phpwordpressloopswoocommerce

解决方案


问题出在foreach 循环中,每个循环都将 用下一个产品的产品名称覆盖当前变量(产品名称)。

例子:

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

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

// Result = world
echo $product_name;

解决方案是连接字符串

所以而不是$variable= something;

使用$variable .= something;

所以你得到

例子:

$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;

解决方案:用以下代码替换您当前的 foreach 循环

$product_name = '';

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

推荐阅读