You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

提交Contact Form 7后创建WooCommerce产品无响应求助

问题

我用Contact Form 7做了一个表单,页面里有个class为btQuoteTotalCalc的span元素,里面是数值。我写了个自定义插件,想在表单提交时用JS捕获这个数值,以此为价格创建WooCommerce产品,然后跳转到结账页,但测试时完全没反应,浏览器控制台和服务器PHP日志都没报错。相关代码如下:

JS文件代码

// Function to capture the number from the page
function captureNumberFromPage() {
    var numberElement = document.querySelector('.btQuoteTotalCalc');
    
    if (numberElement) {
        var number = parseFloat(numberElement.innerText);
        return number;
    }

    // Return null if number not found
    return null;
}

// Attach a function to the wpcf7mailsent event
document.addEventListener('wpcf7mailsent', function(event) {
    // Capture the number from the page
    var capturedNumber = captureNumberFromPage();

    // Check if a number is captured successfully
    if (capturedNumber !== null) {
        // Make an AJAX request to the server to create the WooCommerce product
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/wp-admin/admin-ajax.php?action=create_woocommerce_product');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                // Redirect the user to the checkout page
                window.location.href = 'https://example.com/checkout'; // Replace with your actual checkout page URL
            }
        };
        xhr.send('price=' + capturedNumber);
    } else {
        console.log('Number not found on the page.');
    }
}, false);

主插件PHP文件代码

// Function to create a WooCommerce product
function create_woocommerce_product() {
    if (isset($_POST['price'])) {
        $product_data = array(
            'name' => 'Custom Product', // Replace with the desired product name
            'type' => 'simple',
            'regular_price' => $_POST['price'], // Use the captured number as the product price
            'description' => 'This is a custom product.', // Replace with the desired product description
        );

        // Create the product
        $product_id = wc_create_product($product_data);

        if ($product_id) {
            echo 'Product created successfully.';
        } else {
            echo 'Failed to create product.';
        }
    }

    // Always exit to prevent any extra output
    exit;
}
add_action('wp_ajax_create_woocommerce_product', 'create_woocommerce_product');
add_action('wp_ajax_nopriv_create_woocommerce_product', 'create_woocommerce_product');

注:我已在主插件PHP文件中正确入队了JS文件。


排查与修复步骤

  1. 验证CF7事件触发状态
    在wpcf7mailsent事件回调开头添加console.log('CF7 form submitted');,提交表单后查看控制台是否输出该内容,确认事件是否正常绑定。

  2. 确保数值捕获正常
    在captureNumberFromPage函数中添加日志,排查元素获取和数值解析问题:

    function captureNumberFromPage() {
        var numberElement = document.querySelector('.btQuoteTotalCalc');
        console.log('Target element:', numberElement);
        if (numberElement) {
            console.log('Element text content:', numberElement.innerText);
            // 清理文本中的非数字字符(如货币符号、空格)
            var cleanText = numberElement.innerText.replace(/[^0-9.]/g, '');
            var number = parseFloat(cleanText);
            console.log('Parsed price:', number);
            return number;
        }
        return null;
    }
    
  3. 修复AJAX请求路径
    直接使用/wp-admin/admin-ajax.php在子目录站点下会出错,通过WordPress本地化脚本传递正确路径:

    // 在入队JS的代码后添加
    wp_localize_script('你的JS脚本句柄', 'wp_global_vars', array(
        'ajax_url' => admin_url('admin-ajax.php')
    ));
    

    然后修改JS中的请求地址:

    xhr.open('POST', wp_global_vars.ajax_url + '?action=create_woocommerce_product');
    
  4. 完善AJAX错误处理
    添加错误日志排查请求失败原因:

    xhr.onerror = function() {
        console.error('AJAX请求失败');
    };
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            console.log('AJAX响应状态:', xhr.status);
            console.log('AJAX响应内容:', xhr.responseText);
            if (xhr.status === 200) {
                window.location.href = 'https://example.com/checkout';
            } else {
                console.error('请求失败,状态码:', xhr.status);
            }
        }
    };
    
  5. 补全产品创建与购物车逻辑
    创建产品后必须添加到购物车,否则结账页无商品;同时完善PHP日志和产品状态设置:

    function create_woocommerce_product() {
        error_log('创建产品的AJAX动作触发');
        if (isset($_POST['price'])) {
            error_log('收到的价格: ' . $_POST['price']);
            // 确保WooCommerce全局对象可用
            if (!function_exists('WC')) {
                include_once WP_PLUGIN_DIR . '/woocommerce/woocommerce.php';
            }
            $product_data = array(
                'name' => 'Custom Product',
                'type' => 'simple',
                'regular_price' => $_POST['price'],
                'description' => 'This is a custom product.',
                'status' => 'publish', // 明确设置为发布状态
            );
            $product_id = wc_create_product($product_data);
            error_log('产品创建结果: ' . ($product_id ? $product_id : '失败'));
            
            if ($product_id) {
                // 将产品添加到购物车
                WC()->cart->empty_cart(); // 清空原有购物车(可选)
                WC()->cart->add_to_cart($product_id);
                echo '产品创建并加入购物车成功';
            } else {
                echo '产品创建失败';
            }
        } else {
            error_log('未收到价格参数');
        }
        exit;
    }
    
  6. 验证AJAX权限
    若测试用户未登录,确认wp_ajax_nopriv_create_woocommerce_product动作已正确绑定;登录用户测试则检查wp_ajax_create_woocommerce_product动作。


内容的提问来源于stack exchange,提问作者KWS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 12:52:36