首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WooCommerce中通过Google计算长途运输车费

在WooCommerce中通过Google计算长途运输车费
EN

Stack Overflow用户
提问于 2017-09-21 16:17:28
回答 1查看 1.3K关注 0票数 2

所以,我已经写了一段代码后,得到了一些帮助,从So和互联网。我想通过计算供应商的位置(billing_city)与通过Google Maps API Distance-Matrix的客户区域之间的距离来向购物车添加费用。在这里,我使用下拉列表后,结帐表,以获得客户的面积。

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

代码语言:javascript
复制
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;
}

所以,现在我应该在$_SESSION['dist']中有一个值,并且我应该能够将它传递给同一个页面中的另一个函数。这是我用来计算购物车费用的代码。

代码语言:javascript
复制
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){

    if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if($_SESSION['dist']){
        $customshipcost = $dist_ance;
        if ( is_admin() && ! defined ( 'DOING_AJAX' ))
            WC()->cart->add_fee('Distance Delivery Charge', $customshipcost , true);
    }
}

其实我有两个问题。任何帮助都会很感激的。

  • 有时我从cookie中得到值,有时我没有。我使用echo来检查它是否给了我这个值。
  • 会话没有响应。我在我的车里得到了'0‘作为收费。

FYKI,我现在只想在购物车上显示数字距离。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-22 09:49:08

以下是在woocommerce_cart_calculate_fees操作钩子中获取所选位置值的正确方法。我已经移动了这个钩子函数中的所有php代码。

woocommerce_after_checkout_form动作钩子中挂起的自定义函数中,我添加了修改过的jQuery代码。

我已经测试了所有的东西(但不是google部分和距离计算费),它可以实时运行:每次选择一个值,它都会在费用函数中被更新。

以下是代码:

代码语言:javascript
复制
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);
    }
}

代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。

所有代码都是在Woocommerce 3+上进行测试和工作的。

这将解决您的coockie和会话问题

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46348735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档