如何阻止WooCommerce跳转到感谢页并在结账页获取订单数据?
阻止WooCommerce跳转感谢页并在结账页展示订单数据的实现方案
1. 拦截结账表单默认提交行为
通过jQuery监听结账表单的提交事件,在表单验证通过后阻止默认跳转,改用AJAX提交订单请求,避免页面跳转。
jQuery(document).ready(function($) { // 监听结账表单提交 $('form.checkout').on('submit', function(e) { // 仅在WooCommerce表单验证无错误时拦截 if ($('.woocommerce-error').length === 0) { e.preventDefault(); const form = $(this); const formData = form.serialize(); // 发送AJAX提交订单 $.ajax({ type: 'POST', url: wc_checkout_params.checkout_url, data: formData + '&action=woocommerce_checkout', beforeSend: () => { // 添加加载遮罩 form.block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6 } }); }, success: (response) => { if (response.result === 'success') { // 获取订单数据并展示感谢信息 displayThankYouContent(response.order); } else { // 显示提交错误提示 $('.woocommerce-notices-wrapper').html(response.messages || '<div class="woocommerce-error">提交失败,请重试</div>'); } }, error: () => { $('.woocommerce-notices-wrapper').html('<div class="woocommerce-error">网络异常,请稍后再试</div>'); }, complete: () => form.unblock() }); } }); });
2. 渲染感谢信息与订单数据
编写自定义函数,将结账页面内容替换为感谢信息和订单详情,根据AJAX返回的订单数据动态生成内容。
function displayThankYouContent(orderData) { const checkoutContainer = $('div.woocommerce-checkout'); let thankYouHtml = ` <div class="woocommerce-order-received"> <h2>感谢您的订单!</h2> <p>您的订单号:<strong>${orderData.id}</strong></p> <p>我们已收到您的订单,将尽快为您处理。</p> <h3>订单详情</h3> <table class="woocommerce-table shop_table order_details"> <thead> <tr><th>商品</th><th>小计</th></tr> </thead> <tbody> `; // 遍历渲染订单商品 $.each(orderData.line_items, (_, item) => { thankYouHtml += ` <tr class="order_item"> <td class="product-name">${item.name} × ${item.quantity}</td> <td class="product-total">${item.subtotal}</td> </tr> `; }); // 渲染订单总计 thankYouHtml += ` </tbody> <tfoot> <tr class="order-total"> <th>订单总计</th> <td><strong>${orderData.total}</strong></td> </tr> </tfoot> </table> </div> `; // 替换结账页内容 checkoutContainer.html(thankYouHtml); }
3. PHP端补充:完善AJAX返回的订单数据
默认WooCommerce的AJAX响应不包含完整订单数据,需在主题functions.php中添加过滤器,补充所需字段:
add_filter('woocommerce_checkout_update_order_review_response', 'custom_checkout_response_data', 10, 1); function custom_checkout_response_data($response) { if ($response['result'] === 'success') { $order = wc_get_order($response['order_id']); $response['order'] = [ 'id' => $order->get_id(), 'total' => $order->get_formatted_order_total(), 'line_items' => [] ]; // 整理订单商品数据 foreach ($order->get_items() as $item) { $response['order']['line_items'][] = [ 'name' => $item->get_name(), 'quantity' => $item->get_quantity(), 'subtotal' => wc_price($item->get_subtotal()) ]; } } return $response; }
注意事项
- 确保代码在jQuery加载后执行,WooCommerce默认已引入jQuery,无需额外添加。
- 若使用第三方支付网关(如支付宝、微信支付),需针对支付回调逻辑调整,确保支付完成后返回结账页并触发信息渲染。
- 测试时需验证订单状态是否正常生成(如待付款、处理中)。
内容的提问来源于stack exchange,提问作者Sydur Rahman
相关产品推荐
相关产品推荐

