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

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

问题描述

我有一个Contact Form 7表单,页面内存在class为btQuoteTotalCalc的span元素(包含数值)。需求是:提交表单时通过JavaScript/jQuery获取该数值,以此为价格创建WooCommerce产品,然后将用户重定向至结账页面。

所有代码已写入自定义插件,脚本已正确入队,WooCommerce API密钥也已填写,但测试时提交表单无任何反应,浏览器控制台和服务器PHP错误日志均未显示报错信息。

原代码如下:

原JavaScript代码

jQuery(document).ready(function($) {
    $('form#wpcf7-f731').on('submit', function(event) {
        event.preventDefault();

        // Get the number from the nearby span with class 'btQuoteTotalCalc'
        var price = parseFloat($('.btQuoteTotalCalc').text());

        // Create a new WooCommerce product
        $.ajax({
            url: '/wp-json/wc/v3/products',
            method: 'POST',
            data: {
                name: 'Product Name', // Replace with your desired product name
                type: 'simple',
                regular_price: price,
                status: 'publish'
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader('Authorization', 'Basic ' + btoa('YOUR_WC_KEY:YOUR_WC_SECRET'));
            },
            success: function(data) {
                // Redirect the user to the checkout page
                window.location.href = 'https://silkwoodstudios.co.uk/checkout/';
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
    });
});

原插件入队脚本PHP代码

function custom_woocommerce_plugin_enqueue_scripts() {
    if (is_page('product-photography')) {
        wp_enqueue_script('custom-woocommerce-script', plugins_url('custom_woocommerce_plugin/custom_woocommerce_script.js'), array('jquery'), '1.0', true);
    }
}
add_action('wp_enqueue_scripts', 'custom_woocommerce_plugin_enqueue_scripts');

问题分析与修复方案

核心问题点

  1. Contact Form 7事件拦截失效:CF7有自身的AJAX提交机制,直接监听form.submit事件会被覆盖,无法触发自定义逻辑。
  2. 前端暴露API密钥风险:直接在JS中写入WooCommerce API密钥会导致密钥泄露,严重影响站点安全。
  3. REST请求格式错误:直接传递普通对象作为POST数据,未设置正确的content-type,且相对URL可能因站点配置失效。
  4. 缺失购物车环节:创建产品后未添加到购物车,用户跳转结账页时无商品可结算。

修正后的代码

1. 插件主文件PHP代码(含自定义REST接口)

function custom_woocommerce_plugin_enqueue_scripts() {
    if (is_page('product-photography')) {
        $script_path = plugins_url('custom_woocommerce_script.js', __FILE__);
        wp_enqueue_script('custom-woocommerce-script', $script_path, array('jquery'), '1.0', true);
        
        // 传递REST API地址和验证nonce
        wp_localize_script('custom-woocommerce-script', 'wc_custom_data', array(
            'rest_url' => get_rest_url(),
            'nonce' => wp_create_nonce('wp_rest')
        ));
    }
}
add_action('wp_enqueue_scripts', 'custom_woocommerce_plugin_enqueue_scripts');

// 注册自定义REST路由,处理产品创建与购物车添加
add_action('rest_api_init', function() {
    register_rest_route('wc-custom/v1', '/create-product/', array(
        'methods' => 'POST',
        'callback' => 'wc_custom_create_product_and_add_to_cart',
        'permission_callback' => function() {
            return true; // 允许访客操作,可根据需求调整权限
        }
    ));
});

function wc_custom_create_product_and_add_to_cart($request) {
    $price = $request->get_param('price');
    if (!$price || !is_numeric($price) || $price <= 0) {
        return new WP_Error('invalid_price', '无效的价格', array('status' => 400));
    }

    // 创建虚拟产品(适合服务类场景)
    $product_data = array(
        'name' => '定制摄影服务',
        'type' => 'simple',
        'regular_price' => strval($price),
        'status' => 'publish',
        'virtual' => true,
        'downloadable' => false
    );

    $product = wc_create_product($product_data);
    if (is_wp_error($product)) {
        return new WP_Error('create_failed', '产品创建失败', array('status' => 500));
    }

    // 将产品添加到购物车
    WC()->cart->add_to_cart($product->get_id(), 1);

    return array(
        'product_id' => $product->get_id(),
        'checkout_url' => wc_get_checkout_url()
    );
}

2. 修正后的JavaScript代码

jQuery(document).ready(function($) {
    // 监听Contact Form 7专属提交事件
    $(document).on('wpcf7submit', function(event, data) {
        // 仅处理目标表单
        if (data.contactFormId !== '731') return;

        event.preventDefault();

        // 清理价格文本中的非数字字符,避免解析错误
        var priceText = $('.btQuoteTotalCalc').text().replace(/[^0-9.]/g, '');
        var price = parseFloat(priceText);

        if (isNaN(price) || price <= 0) {
            alert('无效的价格,请重新计算');
            return;
        }

        // 调用后端自定义接口
        $.ajax({
            url: wc_custom_data.rest_url + 'wc-custom/v1/create-product/',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ price: price }),
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', wc_custom_data.nonce);
            },
            success: function(res) {
                window.location.href = res.checkout_url;
            },
            error: function(xhr) {
                var errorMsg = xhr.responseJSON ? xhr.responseJSON.message : '请求失败';
                console.error(errorMsg);
                alert('操作失败,请稍后重试');
            }
        });
    });
});

内容的提问来源于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:21:02