WooCommerce 自定义内页结账表单中购物车状态异常的排查与修复

碧海醫心
发布: 2025-07-01 15:06:27
原创
743人浏览过

woocommerce 自定义内页结账表单中购物车状态异常的排查与修复

本文旨在解决WooCommerce自定义内页结账表单在非预览模式下购物车显示为空的问题。核心在于确保WooCommerce购物车会话数据在自定义环境中被正确加载。通过在购物车操作前调用wc_load_cart()函数,可以强制加载并同步当前会话的购物车数据,从而避免因会话未初始化或数据不同步导致的“购物车为空”错误,确保订单能正常处理。

问题描述与技术背景

在开发WordPress网站上集成的WooCommerce自定义内页结账表单时,开发者可能会遇到一个独特的挑战:当用户在产品页面直接填写表单并尝试支付时,系统在预览模式下能正常处理订单,但在非预览模式下(例如在新的浏览器窗口或设备上访问)却会跳转到“购物车为空”页面,导致订单无法生成。

这种现象通常发生在自定义的结账流程中,尤其是当页面不完全遵循WooCommerce标准模板加载机制时。WooCommerce依赖于其内部会话(session)机制来维护用户的购物车状态。在标准的WooCommerce页面加载流程中,购物车会话数据通常会被自动初始化和加载。然而,在高度定制化的页面或插件中,如果缺少必要的初始化步骤,购物车对象可能无法正确地从用户会话中读取其当前状态,从而导致即使已经通过代码添加了商品,前端依然显示购物车为空。预览模式可能由于WordPress或WooCommerce的调试/开发环境配置,隐式地完成了部分会话初始化,从而掩盖了这一问题。

解决方案:强制加载购物车会话

解决此问题的关键在于确保在执行任何购物车操作(如清空购物车或添加商品)之前,WooCommerce的购物车对象已从当前用户会话中加载了最新的数据。WooCommerce提供了一个专门用于此目的的函数:wc_load_cart()。

wc_load_cart() 函数的作用是显式地加载并初始化WooCommerce的购物车会话数据。当在自定义代码中直接操作 WC()->cart 对象时,如果当前请求的会话尚未完全加载购物车信息,那么对购物车进行的任何操作都可能基于一个空或过时的状态。通过在操作前调用 wc_load_cart(),可以强制系统从会话中检索并填充购物车数据,确保后续操作的准确性。

实现步骤与示例代码

在您的自定义内页结账表单的PHP代码中,找到您执行购物车清空和添加商品操作的部分。通常,这会是类似 WC()->cart->empty_cart(); 和 WC()->cart->add_to_cart(...); 的代码行。

原始代码片段(可能存在问题):

// ... 其他代码 ...

WC()->cart->empty_cart();
WC()->cart->add_to_cart($productId, 1, $initialVariation['id']);

// ... 其他代码 ...
登录后复制

修改后的代码片段(添加 wc_load_cart()):

在 WC()->cart->empty_cart(); 之前,添加一行 wc_load_cart();。

<?php
// In page checkout form
setlocale(LC_TIME, "it_IT");

$productId = $GLOBALS['inpage_form_product'];
$options = $GLOBALS['inpage_form_options'];

wp_enqueue_style('inpage-form', get_template_directory_uri() . ($options['inpage_form_style'] ?? '/inpage-form.css'));
wp_enqueue_script('inpage-form', get_template_directory_uri() . '/assets/js/inpage-form.js');

$product = wc_get_product($productId);
$variations = $product->get_available_variations();

$variations = array_map(function ($variation) use ($options) {
    return [
        'id' => $variation['variation_id'],
        'label' => $variation['attributes']['attribute_quantita'],
        'price' => $variation['display_price'],
        'regular_price' => $variation['display_regular_price'],
        'quantity' => strip_tags($variation['variation_description']),
        'highlight' => $options['highlight_label_' . $variation['variation_id']] ?? false,
        'highlight_color' => $options['highlight_label_color_' . $variation['variation_id']] ?? false,
    ];
}, $variations);

$initialVariation = $variations[0];

function formatPrice($price)
{
    echo number_format($price, 2, ',', '') . '€';
}

// 关键修复:在操作购物车前加载购物车会话
wc_load_cart(); 
WC()->cart->empty_cart();
WC()->cart->add_to_cart($productId, 1, $initialVariation['id']);

if(class_exists('WC_Gateway_Stripe')) {
    $stripe = new WC_Gateway_Stripe();

    $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '' : '.min';
    wp_register_style('stripe_styles', plugins_url('assets/css/stripe-styles.css', WC_STRIPE_MAIN_FILE), [], WC_STRIPE_VERSION);
    wp_enqueue_style('stripe_styles');

    wp_register_script('stripe', 'https://js.stripe.com/v3/', '', '3.0', true);
    wp_register_script('woocommerce_stripe', plugins_url('assets/js/stripe' . $suffix . '.js', WC_STRIPE_MAIN_FILE), ['jquery-payment', 'stripe'], WC_STRIPE_VERSION, true);
    wp_register_script('woocommerce_gateway_stripe', plugins_url('assets/js/stripe' . $suffix . '.js', WC_STRIPE_MAIN_FILE), ['jquery-payment', 'stripe'], WC_STRIPE_VERSION, true);

    wp_localize_script(
        'woocommerce_stripe',
        'wc_stripe_params',
        apply_filters('wc_stripe_params', $stripe->javascript_params())
    );

    $stripe->tokenization_script();
    wp_enqueue_script('woocommerce_stripe');
}


wp_enqueue_script('wc-country-select');
wp_enqueue_script('selectWoo');
wp_enqueue_style('select2');

$shippingMethods = WC()->shipping()->get_packages()[0]['rates'];
$chosenMethod = isset(WC()->session->chosen_shipping_methods[0]) ? WC()->session->chosen_shipping_methods[0] : '';

function business_day($days, $abbrv = false)
{
    if($abbrv) {
        return utf8_encode(strtolower(strftime('%a %e. %m.', strtotime(" $days weekdays"))));
    }
    return utf8_encode(strtolower(strftime('%A', strtotime(" $days weekdays"))));
}

function add_delivery_payment_info()
{
    printf('<div class="inpage-form__delivery_payment">');
    printf('<div class="inpage-form__delivery_payment__wrapper">');
    printf('<div>');
    printf('<div class="inpage-form__delivery_payment__title">Oggi non paghi niente!</div>');
    printf('<div class="inpage-form__delivery_payment__description">Paghi alla consegna ?</div>');
    printf('</div>');
    printf('
    <svg enable-background="new 0 0 24 24" height="512" viewBox="0 0 24 24" width="512" xmlns="http://www.w3.org/2000/svg"><path d="m19 4.86-8.991 4.383-3.501-1.701-1.458-.711-4.05-1.971 8.991-4.374 3.834 1.864 1.53.738z" fill="#ffa726"/><path d="m9.99 19.779-9.49-4.939v-9.48l9.49 4.37z" fill="#ffcc80"/><path d="m19.5 5.36v9.48l-9.49 4.939v-10.049z" fill="#ffb74d"/><path d="m17.5 23.4c-.142 0-.283-.044-.403-.133-.558-.415-5.447-4.141-5.447-7.302 0-1.855 1.514-3.364 3.375-3.364.957 0 1.848.401 2.475 1.074.627-.673 1.518-1.074 2.475-1.074 1.861 0 3.375 1.509 3.375 3.364 0 3.161-4.89 6.888-5.447 7.302-.12.089-.261.133-.403.133z" fill="#f44336"/><path d="m17.5 24c-.157 0-.314-.05-.447-.148-.62-.46-6.053-4.601-6.053-8.114 0-2.061 1.682-3.738 3.75-3.738 1.063 0 2.054.446 2.75 1.194.696-.748 1.687-1.194 2.75-1.194 2.068 0 3.75 1.677 3.75 3.738 0 3.513-5.433 7.653-6.053 8.113-.133.099-.29.149-.447.149zm-2.75-10.5c-1.241 0-2.25 1.004-2.25 2.238 0 2.142 3.276 5.191 5 6.564 1.724-1.374 5-4.427 5-6.564 0-1.234-1.009-2.238-2.25-2.238-.897 0-1.707.527-2.062 1.343-.238.547-1.137.547-1.375 0-.356-.816-1.166-1.343-2.063-1.343z"/><path d="m10.007 10.5c-.278 0-.545-.155-.675-.422-.181-.372-.026-.821.346-1.002l9.244-4.5c.234-.114.507-.099.726.039.219.136.352.377.352.635v4c0 .414-.336.75-.75.75s-.75-.336-.75-.75v-2.801l-8.166 3.975c-.105.052-.217.076-.327.076z"/><path d="m9.25 20c-.125 0-.25-.03-.366-.096l-8.5-4.75c-.237-.132-.384-.383-.384-.654v-9.25c0-.258.133-.499.353-.636.218-.138.493-.153.726-.039l9.244 4.5c.373.181.527.63.346 1.002-.182.373-.632.525-1.002.346l-8.167-3.974v7.61l8.116 4.536c.362.201.491.658.289 1.021-.137.245-.393.384-.655.384z"/><path d="m.75 6c-.277 0-.544-.155-.674-.422-.181-.372-.026-.821.346-1.002l9.244-4.5c.207-.101.449-.101.656 0l9.256 4.5c.373.181.527.63.346 1.002s-.629.529-1.002.346l-8.928-4.34-8.916 4.34c-.105.052-.217.076-.328.076z"/><path d="m5.25 11.99c-.414 0-.75-.336-.75-.75v-3.8c0-.283.16-.542.413-.67l9.09-4.581c.369-.186.82-.038 1.007.333.186.37.038.821-.333 1.007l-8.677 4.373v3.338c0 .414-.336.75-.75.75z"/></svg>');
    printf('</div>');
    printf('</div>');
}

add_action('woocommerce_review_order_before_submit', 'add_delivery_payment_info');

?>
<div class="inpage-form" data-product-id="<?php echo $productId; ?>">
    <div class="inpage-form__form-card">
        <h4>Modulo d’ordine</h4>
        <div class="inpage-form__total">
            <span class="inpage-form__regular-price"><?php formatPrice($initialVariation['regular_price']); ?></span>
            <span class="inpage-form__price"><?php formatPrice($initialVariation['price']); ?></span>
        </div>
        <!--<div class="inpage-form__countdown">
            <svg enable-background="new 0 0 24 24" height="512" viewBox="0 0 24 24" width="512"
                 xmlns="http://www.w3.org/2000/svg" fill="currentColor">
                <path d="m6.5 19h-2c-.276 0-.5-.224-.5-.5s.224-.5.5-.5h2c.276 0 .5.224.5.5s-.224.5-.5.5z"/>
                <path d="m22.75 19h-1.25c-.276 0-.5-.224-.5-.5s.224-.5.5-.5h.835l.674-3.592c-.009-1.838-1.579-3.408-3.509-3.408h-3.283l-1.591 7h2.874c.276 0 .5.224.5.5s-.224.5-.5.5h-3.5c-.152 0-.296-.069-.391-.188-.095-.118-.131-.274-.097-.422l1.818-8c.052-.229.254-.39.488-.39h3.682c2.481 0 4.5 2.019 4.5 4.5l-.759 4.092c-.044.237-.25.408-.491.408z"/>
                <path d="m19.5 21c-1.378 0-2.5-1.121-2.5-2.5s1.122-2.5 2.5-2.5 2.5 1.121 2.5 2.5-1.122 2.5-2.5 2.5zm0-4c-.827 0-1.5.673-1.5 1.5s.673 1.5 1.5 1.5 1.5-.673 1.5-1.5-.673-1.5-1.5-1.5z"/>
                <path d="m8.5 21c-1.378 0-2.5-1.121-2.5-2.5s1.122-2.5 2.5-2.5 2.5 1.121 2.5 2.5-1.122 2.5-2.5 2.5zm0-4c-.827 0-1.5.673-1.5 1.5s.673 1.5 1.5 1.5 1.5-.673 1.5-1.5-.673-1.5-1.5-1.5z"/>
                <path d="m6.5 10h-4c-.276 0-.5-.224-.5-.5s.224-.5.5-.5h4c.276 0 .5.224.5.5s-.224.5-.5.5z"/>
                <path d="m6.5 13h-5c-.276 0-.5-.224-.5-.5s.224-.5.5-.5h5c.276 0 .5.224.5.5s-.224.5-.5.5z"/>
                <path d="m6.5 16h-6c-.276 0-.5-.224-.5-.5s.224-.5.5-.5h6c.276 0 .5.224.5.5s-.224.5-.5.5z"/>
                <path d="m14 19h-3.5c-.276 0-.5-.224-.5-.5s.224-.5.5-.5h3.101l2.272-10h-11.373c-.276 0-.5-.224-.5-.5s.224
登录后复制

以上就是WooCommerce 自定义内页结账表单中购物车状态异常的排查与修复的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号