如何在钩子中访问WooCommerce自定义计费字段

时间:2022-10-25 11:06:19

I'm writing a custom WordPress function that will change the flat_rate shipping when a customer changes the "State" field from a select menu. Currently I'm doing it in my theme's functions.php

我正在编写一个自定义WordPress功能,当客户从选择菜单更改“状态”字段时,该功能将更改flat_rate运输。目前我在我的主题的functions.php中这样做

I have created a custom field to represent "State" field as a drop down menu in the billing fields. I used "WooCommerce Checkout Manager" plugin to setup the custom field and disabled the default "State" field.

我创建了一个自定义字段,将“状态”字段表示为计费字段中的下拉菜单。我使用“WooCommerce Checkout Manager”插件来设置自定义字段并禁用默认的“State”字段。

Now I want to change the shipping cost depending on the value of my custom "State" field. I'm unable to retrieve the data of the field. Also I want to know what hook I can use to change the flat rate shipping once this field's value is changed.

现在我想根据自定义“状态”字段的值更改运费。我无法检索该字段的数据。此外,我想知道一旦该字段的值发生变化,我可以用什么钩子来改变统一费率。

I've used this filter hook (woocommerce_package_rates) and it doesn't work.

我已经使用过这个过滤器钩子(woocommerce_package_rates)而且它不起作用。

Here is my code to do it which I got it from another tutorial then made my customization

这是我的代码,我从另一个教程得到它然后进行自定义

function wc_ninja_change_flat_rates_cost( $rates, $package ) {
$destination = $package['destination'];
$city = $destination['myfield12']; // getting the city field value

// Make sure flat rate is available

if ( isset( $rates['flat_rate'] ) ) {

    if ( $city == 'Alex' || $city == 'الإسكندرية' ) {
        // Set flat rate to cost $10 more
        $rates['flat_rate']->cost = 30;
    }
    else {
        $rates['flat_rate']->cost = 20;
    }
}

return $rates;
}
add_filter( 'woocommerce_package_rates', 'wc_ninja_change_flat_rates_cost', 10, 2 );

1 个解决方案

#1


-1  

I found this:

我找到了这个:

http://phpwpinfo.com/how-to-update-shipping-cost-in-cart-dynamically-based-on-a-custom-field-in-woocommerce/

http://phpwpinfo.com/how-to-update-shipping-cost-in-cart-dynamically-based-on-a-custom-field-in-woocommerce/

Basically it captures the field data through JS and send an Ajax request to the server which then stores the value in the session. Then adds an additional fee. It is not exactly what I was seeking to do but its a functional workaround.

基本上它通过JS捕获字段数据并向服务器发送Ajax请求,然后服务器将值存储在会话中。然后再增加一笔费用。这不是我想要做的,而是一个功能性的解决方法。

#1


-1  

I found this:

我找到了这个:

http://phpwpinfo.com/how-to-update-shipping-cost-in-cart-dynamically-based-on-a-custom-field-in-woocommerce/

http://phpwpinfo.com/how-to-update-shipping-cost-in-cart-dynamically-based-on-a-custom-field-in-woocommerce/

Basically it captures the field data through JS and send an Ajax request to the server which then stores the value in the session. Then adds an additional fee. It is not exactly what I was seeking to do but its a functional workaround.

基本上它通过JS捕获字段数据并向服务器发送Ajax请求,然后服务器将值存储在会话中。然后再增加一笔费用。这不是我想要做的,而是一个功能性的解决方法。