Php 在WooCommerce中通过Google API计算距离运输车费用

Php 在WooCommerce中通过Google API计算距离运输车费用,php,wordpress,woocommerce,checkout,cart,Php,Wordpress,Woocommerce,Checkout,Cart,所以,在得到So和internet的帮助后,我写了一段代码。我想通过谷歌地图API距离矩阵计算供应商所在地(billing_city)与客户所在区域之间的距离,从而向购物车中添加费用。在这里,我使用帐单后的下拉列表表单来获取客户区域 我在从cookies获取值并将变量传递给下一个函数时遇到问题。FYKI,我已将此代码插入到我的子主题函数中 add_action( 'wp_footer', 'calculate_distance_between_two_locations' ); function

所以,在得到So和internet的帮助后,我写了一段代码。我想通过
谷歌地图API距离矩阵
计算供应商所在地(
billing_city
)与客户所在区域之间的距离,从而向购物车中添加费用。在这里,我使用帐单后的下拉列表表单来获取客户区域

我在从cookies获取值并将变量传递给下一个函数时遇到问题。FYKI,我已将此代码插入到我的子主题函数中

add_action( 'wp_footer', 'calculate_distance_between_two_locations' );
function calculate_distance_between_two_locations($dist) {

    // I am getting first item of the cart
    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_id = $cart_item['product_id']; 
        break; 
    }

    //Now I am fetching vendor's id and location of the item
    $vendor_id = get_post_field( 'post_author', $product_id );
    $vendor_location = get_user_meta($vendor_id, 'billing_city', true);

    //Here I'm fetching the value from customer location
    //I am using a dropdown/select named billing_myfield5
    if (is_checkout()) {?>
        <script type="text/javascript">
        jQuery( document ).ready(function( $ ) {
            $('#billing_myfield5').change(function(){
            jQuery('body').trigger('update_checkout');
                var location = $('#billing_myfield5 option:selected').text();
                document.cookie="cusarea="+location;
        });
    });
    </script>
    <?php
    }

    //Encoding the customer's location for Google API 
    //and putting it into a variable 
    $customer_area = rawurlencode($_COOKIE ['cusarea']);

    //I am setting Google API
    $shippingurl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$vendor_location."&destinations=".$customer_area."&key=MY_API_KEY";

    //Now fetching json response from googleapis.com:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $shippingurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);
    //If google responds with a status of OK
    //Extract the distance text:
    if($response['status'] == "OK"){
        $dist = $response['rows'][0]['elements'][0]['distance']['text'];
    }

    //Getting the integers from the string
    $dist_ance = preg_replace("/[^0-9\.]/", '', $dist);

    //Finally putting the value in session
    session_start();
    $_SESSION['dist'] = $dist_ance;
}
嗯,实际上我有两个问题。任何帮助都将不胜感激

  • 有时我从cookie中得到值,有时我没有。我用回声 检查它是否给了我值
  • 会话没有响应。我的购物车中的费用为“0”

FYKI,我现在只是想在购物车中只显示数字距离作为费用

以下是在
woocommerce\u cart\u calculate\u fees
操作挂钩中获取所选位置值的正确方法。我已经移动了这个挂钩函数中的所有php代码

在签出表单操作钩子后的一个自定义函数中,我添加了修改后的jQuery代码

我已经测试了一切(但没有谷歌API部分和距离计算费用),它可以实时工作:每次选择一个值,它都会在费用函数中更新

代码如下:

add_action( 'woocommerce_after_checkout_form', 'custom_checkout_jquery_script', 10 );
function custom_checkout_jquery_script() {
    // Setting the country in customer data and session
    $country_code = 'BD'; // For Bangladesh
    WC()->session->set( 'country', $country_code );
    WC()->session->set( 'billing_country', $country_code );
    WC()->session->set( 'shipping_country', $country_code );
    WC()->customer->set_billing_country( $country_code );
    WC()->customer->set_shipping_country( $country_code );

    // The jQuery code
    ?>
    <script type="text/javascript">
        (function($){
            // Initializing (get the default value)
            var location = $('#billing_myfield5 option:selected').html();
            document.cookie="cusarea="+location;
            // To test the default location output in browser console dev tools
            console.log('Selected Area: '+location);

            // Get the live value when selected
            $( 'form.checkout' ).on( 'change', '#billing_myfield5', function(){
                location = $('#billing_myfield5 option:selected').html();
                document.cookie="cusarea="+location;
                $('body').trigger('update_checkout');
                // To test the selected location output in browser console dev tools
                console.log('Selected Area: '+location);
            });
        })(jQuery);
    </script>
    <?php
}

add_action( 'woocommerce_cart_calculate_fees', 'distance_shipping_fee', 10, 1 );
function distance_shipping_fee( $wc_cart ){

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if( empty($_COOKIE ['cusarea']) ) return; // Waiting for the selected area (cookie)
    else $cookie = $_COOKIE ['cusarea'];

    // Encoding the customer's location for Google API
    $customer_area = rawurlencode( $cookie );

    // I am getting first item of the cart
    foreach( $wc_cart->get_cart() as $cart_item ){
        $product_id = $cart_item['product_id'];
        break;
    }

    // Get the vendor's id and location
    $vendor_id = get_post_field( 'post_author', $product_id );
    $vendor_location = get_user_meta($vendor_id, 'billing_city', true);

    // Setting Google API URL ##
    $gapi_key = "MY_API_KEY"; // Set HERE your google api key
    $shippingurl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$vendor_location";
    $shippingurl .= "&destinations=$customer_area&key=$gapi_key";

    // Now fetching json response from googleapis:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $shippingurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);

    // If google responds with a status of OK: Extract the distance text:
    if($response['status'] == "OK")
        $dist = $response['rows'][0]['elements'][0]['distance']['text'];

    // Getting the integers from the string
    $distance = preg_replace("/[^0-9\.]/", '', $dist);

    if( $distance > 0 ){
        $customshipcost = $distance;
        // Displaying the selected location in the fee label
        $wc_cart->add_fee( "Distance Delivery fee ($cookie)", $customshipcost , true);
    }
}
add_action('woocommerce_-after_-checkout_-form','custom_-checkout_-jquery_-script',10);
函数自定义\u签出\u jquery\u脚本(){
//在客户数据和会话中设置国家/地区
$country_code='BD';//孟加拉国
WC()->session->set('country',$country\u代码);
WC()->session->set('billing\u country',$country\u code);
WC()->session->set('shipping\u country',$country\u code);
WC()->customer->set\u billing\u country($country\u code);
WC()->customer->set_shipping_country($country_code);
//jQuery代码
?>
(函数($){
//正在初始化(获取默认值)
var location=$(“#计费_myfield5选项:选中”).html();
document.cookie=“cusarea=”+位置;
//在浏览器控制台开发工具中测试默认位置输出的步骤
console.log('所选区域:'+位置);
//选择时获取活动值
$('form.checkout')。在('change','#billing_myfield5',function()上{
location=$('#billing_myfield5选项:selected').html();
document.cookie=“cusarea=”+位置;
$('body')。触发器('update_checkout');
//在浏览器控制台开发工具中测试选定位置输出的步骤
console.log('所选区域:'+位置);
});
})(jQuery);

非常感谢。太棒了!我真的很感谢您为使其工作所做的努力:)在woocommerce最近更新后,此代码出现问题。您能帮忙吗?在Skype上敲了你一下。提前谢谢。
add_action( 'woocommerce_after_checkout_form', 'custom_checkout_jquery_script', 10 );
function custom_checkout_jquery_script() {
    // Setting the country in customer data and session
    $country_code = 'BD'; // For Bangladesh
    WC()->session->set( 'country', $country_code );
    WC()->session->set( 'billing_country', $country_code );
    WC()->session->set( 'shipping_country', $country_code );
    WC()->customer->set_billing_country( $country_code );
    WC()->customer->set_shipping_country( $country_code );

    // The jQuery code
    ?>
    <script type="text/javascript">
        (function($){
            // Initializing (get the default value)
            var location = $('#billing_myfield5 option:selected').html();
            document.cookie="cusarea="+location;
            // To test the default location output in browser console dev tools
            console.log('Selected Area: '+location);

            // Get the live value when selected
            $( 'form.checkout' ).on( 'change', '#billing_myfield5', function(){
                location = $('#billing_myfield5 option:selected').html();
                document.cookie="cusarea="+location;
                $('body').trigger('update_checkout');
                // To test the selected location output in browser console dev tools
                console.log('Selected Area: '+location);
            });
        })(jQuery);
    </script>
    <?php
}

add_action( 'woocommerce_cart_calculate_fees', 'distance_shipping_fee', 10, 1 );
function distance_shipping_fee( $wc_cart ){

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if( empty($_COOKIE ['cusarea']) ) return; // Waiting for the selected area (cookie)
    else $cookie = $_COOKIE ['cusarea'];

    // Encoding the customer's location for Google API
    $customer_area = rawurlencode( $cookie );

    // I am getting first item of the cart
    foreach( $wc_cart->get_cart() as $cart_item ){
        $product_id = $cart_item['product_id'];
        break;
    }

    // Get the vendor's id and location
    $vendor_id = get_post_field( 'post_author', $product_id );
    $vendor_location = get_user_meta($vendor_id, 'billing_city', true);

    // Setting Google API URL ##
    $gapi_key = "MY_API_KEY"; // Set HERE your google api key
    $shippingurl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$vendor_location";
    $shippingurl .= "&destinations=$customer_area&key=$gapi_key";

    // Now fetching json response from googleapis:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $shippingurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);

    // If google responds with a status of OK: Extract the distance text:
    if($response['status'] == "OK")
        $dist = $response['rows'][0]['elements'][0]['distance']['text'];

    // Getting the integers from the string
    $distance = preg_replace("/[^0-9\.]/", '', $dist);

    if( $distance > 0 ){
        $customshipcost = $distance;
        // Displaying the selected location in the fee label
        $wc_cart->add_fee( "Distance Delivery fee ($cookie)", $customshipcost , true);
    }
}