如何将前端div展示的订单总价传递到WordPress的PHP mail函数中
解决方案
第一步:修改前端表单代码
div标签的内容不会随表单自动提交到后端,你需要新增一个隐藏输入框用来同步存储总价数据:
- 在你现有展示总价的div下方加入隐藏输入框:
<div name="totalPrice" id="totalPrice" class="totalPrice">0</div> <!-- 新增隐藏输入框 --> <input type="hidden" name="totalPrice" id="totalPriceInput" value="0">
- 修改你前端计算总价的JS脚本,每次更新div展示的总价时,同步更新隐藏输入框的值:
// 你原有的总价计算逻辑 let calculatedTotal = 你的总价计算结果; // 原有更新展示的代码 document.getElementById('totalPrice').innerText = calculatedTotal; // 新增同步更新隐藏输入框的代码 document.getElementById('totalPriceInput').value = calculatedTotal;
如果你的表单是通过AJAX提交,不需要加隐藏输入框,直接在AJAX提交的参数里新增totalPrice: document.getElementById('totalPrice').innerText即可。
第二步:修改functions.php代码
修改你的提交逻辑,接收前端传过来的总价参数,同时修复原有代码的逻辑问题:
function submit_form() { if(isset($_POST['submit_form'])) { $str = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT); $gender = $_POST['gender']; $name = $_POST['username']; $phone = $_POST['phone']; $email = $_POST['email']; $deliverydate = $_POST['deliverydate']; $deliverytime = $_POST['deliverytime']; $payment = $_POST['payment']; $address1 = $_POST['address1']; $address2 = $_POST['address2']; // 新增接收总价参数,做格式转换和基础校验 $totalPrice = isset($_POST['totalPrice']) ? floatval($_POST['totalPrice']) : 0; $totalPrice = $totalPrice < 0 ? 0 : $totalPrice; $item_ids = json_decode(stripslashes($_POST['submit_form'])); $itemid = $_POST['itemid']; $qty = $_POST['qty']; $item_names = []; $items = "Item - Qty\n"; foreach($item_ids as $item) { foreach($item as $k => $i) { $item_names[$k] = $i; } } foreach($itemid as $k => $itm) { if(isset($item_names[$itm])) { $items .= $item_names[$itm] .' - '. $qty[$k]."\n"; } } $message = ""; $message .= "Order No - $str\n"; $message .= "Name - $gender $name\n"; $message .= "Phone - $phone\n"; $message .= "Email - $email\n"; $message .= "Delivery Date - $deliverydate\n"; $message .= "Delivery Time - $deliverytime\n"; $message .= "Address - $address1 $address2\n"; $message .= "Payment - $payment\n"; $message .= "-----------------------\n"; $message .= $items; $message .= "-----------------------\n"; $message .= "Total - $totalPrice\n"; $admin_mail = 'email@gmail.com'; $to = $email; $subject = "New Order"; $headers = ''; $headers .= 'From: xxx@xxx.com '. "\r\n"; $headers .= 'Reply-To:'. $email . "\r\n"; // 把邮件发送逻辑移到提交判断内,避免无提交时触发报错 $sent = mail($admin_mail, $subject, $message, $headers); if($sent) { //echo "sent <br>"; } else { //echo "failed"; } $sent = mail($to, $subject, $message, $headers); if($sent) { //echo "sent <br>"; } else { //echo "failed"; } } } add_action( 'init', 'submit_form' );
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

