首页 文章

woocommerce - 根据地址字段更新运费

提问于
浏览
0

我有一家餐馆,我正在开发一个在线订购食品的网站 . 我正在为网站使用woocommerce .

由于我们只能在城市内的有限区域进行交付,因此我将地址线2定制为一个完整的可由我们交付的区域的下拉列表 .

我已经做了很多 .

现在我需要的是,根据从下拉列表中选择的区域更新运费 .

我是wordpress和php的新手,所以精心解释的答案很受欢迎 .

提前致谢

Edit:

我做了一些研究,找到了更新运费的方法

add_action( 'woocommerce_flat_rate_shipping_add_rate','add_another_custom_flat_rate', 10, 2 );

function add_another_custom_flat_rate( $method, $rate ) {
$new_rate          = $rate;
$new_rate['cost']  = 50; // Update the cost to 50
$method->add_rate( $new_rate );
}

但我仍然坚持如何在这个函数中获取区域名称,我尝试使用 $fields['billing']['billing_address_2'] 来引用它,但这不起作用 .

如果有人可以帮助我获得该功能中的地址第2行,那将非常有用 .

TIA

Edit 2: 我've modified a code from the answer to my need, for now, I'我没有使用DB获取下拉值,只是硬编码 . 由于这是wordpress,因此字段已经存在,我只能使用它们 . 下面是略微修改的jQuery我'm using, I'已将其保存在我的子主题中为updateshipping.js:

<script>
$("#billing_address_2").change(function () {
/* ajax function */
var area =  $("#billing_address_2").val();

$.ajax({
    url: 'functions.php',
    method: 'POST',
    data: { field1: area} ,
    contentType: 'application/json; charset=UTF-8',
    success: function (response) {
        alert(response.status);
        $("#order_review").val(response);
    },

}); 
}
</script>

billing_address_2<select> id

order_review 是我需要刷新的div id

我还要在functions.php中引入js,如下所示:

add_action( 'wp_enqueue_scripts', 'update_shipping' );

function update_shipping() {

wp_register_script( 'updateshipping', get_stylesheet_directory_uri(). '/updateshipping.js',array('jquery') );
wp_enqueue_script( 'updateshipping' );

 }

现在,我在上面给出的add_another_custom_flat_rate函数中添加了这一行:

$area = $_REQUEST['area'];
echo $area;

但由于某种原因,该地区没有得到 . 有什么我做错了吗?

请帮助,提前致谢

1 回答

  • 0

    你可以用ajax / javascript来解决你的问题,

    • 创建你的php文件,
    <select id = "address_cmbo" value =''>
     <option>query out the values from your database </option>
    </select>
    
    <input type="text" value = "" id="cost_textbox" >
    
    • 使用javascript / jquery创建一个函数,
    $("#address_cmbo").change(function () {
                
        /* ajax function */
        
        var address =  $("#address_cmbo").val();
    
        $.ajax({
            url: 'functions.php',
            type: 'POST',
            data: { field1: address} ,
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                alert(response.status);
                $("#cost_textbox").val(response);
            },
    
        }); 
       }
    
    $address_value =   $_REQUEST['address'];
     $query = "Select cost from tbl_address ";
     $result = mysql_query($query);
    
     while( -> mysql_fetch_array){ 
    ---  display the actual cost from the result
     $cost =  $rows['cost'];
    }
    
    • 文本框的值现在将根据所选地址而变化 .

相关问题