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

基于Google Maps API的自定义费用商品添加至WooCommerce购物车问题

问题:基于Google Maps API计算费用并添加自定义商品到WooCommerce购物车失败

我编写了基于Google Maps API的代码,用于计算两地之间的距离并生成对应费用,期望点击提交按钮后,将该费用对应的内容作为自定义商品添加到WooCommerce购物车中。我的思路是点击提交时,创建一个能获取距离和费用输出值的商品并添加至购物车,但编写的相关PHP与JS代码无法实现该功能。以下是我编写的完整代码(未包含Google Maps API密钥):

PHP代码部分

function add_fixed_text_product_to_cart( $cost ) {
    global $woocommerce;

    $product_id = 1825; //固定文本商品的ID
    $product = wc_get_product( $product_id );

    if ( $product ) {
        $woocommerce->cart->add_to_cart( $product_id, 1, 0, array(), array( 'cost' => $cost ) );
    }
}

add_action( 'wp_ajax_add_fixed_text_product_to_cart', 'add_fixed_text_product_to_cart' );
add_action( 'wp_ajax_nopriv_add_fixed_text_product_to_cart', 'add_fixed_text_product_to_cart' );

function add_custom_price_to_cart_item( $cart_object ) {
    if ( is_admin() ) {
        return;
    }

    foreach ( $cart_object->cart_contents as $key => $value ) {
        if ( isset( $value['cost'] ) ) {
            $value['data']->set_price( $value['cost'] );
        }
    }
}

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price_to_cart_item', 10, 1 );


function zip_code_input_shortcode()
{
    ob_start();
    ?>
    <input id="address" type="text" placeholder="Enter address" style="text-align: center;">
    <div id="address-dropdown"></div>
    <div id="output">
        <span id="distance_result"></span>
        <br><br>
        <span id="cost_result"></span>
        <br><br>
        <button id="submit_zipcode">Submit</button>
    </div>
    <script>
jQuery(document).ready(function() {
    jQuery('#submit_zipcode').click(function() {
        // 获取计算出的费用
        var cost = parseFloat(jQuery('#cost_result').text().split(' ')[1].replace(',', '.'));

        // 将信息作为固定文本添加到WooCommerce购物车
        jQuery.ajax({
            url: '/wp-admin/admin-ajax.php',
            data: {
                 'action': 'add_fixed_text_product_to_cart',
            'cost': cost
        },
        success: function(data) {
            console.log(data);
        }
    });
});
</script>
    <?php
    return ob_get_clean();
}

Google Maps相关JS代码

function initMap() {
    var startingLocation = new google.maps.LatLng(55.84336022202228, 9.835100295423425);

    var input = document.getElementById('address');
    var options = {
        types: ['address'],
        componentRestrictions: { country: 'dk' }
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);

    autocomplete.addListener('place_changed', function () {
        var place = autocomplete.getPlace();
        var destination = place.formatted_address;
        var destination_lat = place.geometry.location.lat();
        var destination_lng = place.geometry.location.lng();
        var postal_code = "";

        // 从地址组件中获取邮政编码
        for (var i = 0; i < place.address_components.length; i++) {
            var addressType = place.address_components[i].types[0];
            if (addressType === "postal_code") {
                postal_code = place.address_components[i].long_name;
            }
        }

        // 检查邮政编码是否在1000到4999范围内
        if (postal_code >= 999 && postal_code <= 4999) {
            alert("Vi montere desværre ikke varmepumper på Sjælland.");
            return;
        }

        var service = new google.maps.DistanceMatrixService();
        service.getDistanceMatrix({
            origins: [startingLocation],
            destinations: [destination],
            travelMode: 'DRIVING',
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
        }, function (response, status) {
            if (status === 'OK') {
                var distance_result = response.rows[0].elements[0].distance.text;
                var distance_value = response.rows[0].elements[0].distance.value / 1000;
                distance_value = distance_value.toFixed(2);

                if (distance_value <= 25) {
                    var cost = 0;
                } else {
                    var cost = (distance_value - 25) * 5.95;
                    cost = cost.toFixed(2);
                }

                document.getElementById('distance_result').innerHTML = 'Distance: ' + distance_result;
                document.getElementById('cost_result').innerHTML = 'Cost: ' + cost.toString().replace('.', ',') + ' Danish kroner';

            } else {
                alert('Error: ' + status);
            }
        });
    });
}

我尝试编写了一段JS代码来实现该功能,但未能成功:

jQuery(document).ready(function() {
    jQuery('#submit_zipcode').click(function() {
        // 获取计算出的费用
        var cost = parseFloat(jQuery('#cost_result').text().split(' ')[1].replace(',', '.'));

        // 将信息作为固定文本添加到WooCommerce购物车
        jQuery.ajax({
            url: '/wp-admin/admin-ajax.php',
            data: {
                'action': 'add_fixed_text_product_to_cart',
                'cost': cost
            },
            success: function(data) {
                console.log(data);
            }
        });
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:35:14