php - 获取所有 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) 部分仅在订单中只有一个产品时才会显示某些内容。如果有多个产品,则“项目”不显示任何内容。
我究竟做错了什么?
解决方案
问题出在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() . ' - ';
}
推荐阅读
- d3.js - 使用 D3 并通过附加 SVG 绘制两个圆圈
- python - Windows 10:我将 repo 克隆到本地 Windows pc 后无法安装 Python Github 模块
- node.js - MongoDB 聚合:如何在 MongoDB 聚合中应用分页
- r - 在 MacOS Catalina 中安装 R 包时缺少 gfortran
- python - Python - 从大字符串中解析重复的模式
- angular - 如何在 Angular 7 中显示任何系统格式的日期格式?
- cmake - cmake 的 OpenMPI 基目录的位置
- ruby-on-rails - 阶段中的 NoMethodError#edit
- javascript - 当用户单击推送通知时打开 TWA 应用程序而不是 Web 应用程序
- c++ - 函数模板返回类型