我想根据用户在运费区域表格中添加的额外字段中输入的值来计算运费。我添加了一个名为“ district”的自定义字段,并使用此教程Create a Custom Shipping Method for WooCommerce创建了一种自定义方法来扩展WC_Shipping_Method。
但是作者使用的是$country = $package["destination"]["country"];
中的值,在软件包中,您可以只使用国家,州,城市和邮政编码。我尝试使用$country = $package["destination"]["ciry"];
并成功了,但是当我尝试使用自定义字段时,没有任何障碍。
如何从我的自定义字段“区”中获取一个值以在我的自定义方法中使用?
我看到了这个问题Wordpress Woocommerce get value from custom shipping field (AJAX),但我不知道如何从表单传递值。我试过使用这个:
WC()->checkout->get_value('district')
从这个问题Get fields from checkout form into calculate_shipping开始,但确实无法正常工作。
这是我的自定义字段
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['billing']['district'] = array(
'label' => __('Bairro', 'woocommerce'),
'type' => 'text',
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
$fields['shipping']['district'] = array(
'label' => __('Bairro', 'woocommerce'),
'type' => 'text',
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
这是我自定义的送货方式
function my_custom_shipping_init() {
class my_custom_shipping_method extends WC_Shipping_Method {
public function __construct() {
$this->id = 'my_custom_shipping';
$this->method_title = __('Taxa de entregas por bairros', 'my-custom-shipping');
$this->enabled = 'yes';
$this->title = __('Taxa de entregas por bairros', 'my-custom-shipping');
$this->method_description = __('Plugin to calculate My Custom Shipping Cost', 'my-custom-shipping');
}
function calculate_shipping( $pakage = array() ) {
$shipping_cost = 0;
$destination_district = WC()->checkout->get_value( 'district' );
switch($destination_district){
case 'Guaramirim': $shipping_cost = 5; break;
case 'Beta': $shipping_cost = 7; break;
}
$this->add_rate(array('id' => 'my_custom_shipping',
'label' => 'Taxa de Entrega',
'cost' => $shipping_cost,
'taxes' => '',
'calc_tax' => 'per_order'));
}
}
}
add_action( 'woocommerce_shipping_init', 'my_custom_shipping_init' );
function my_custom_shipping_method( $methods ) {
$methods[] = 'my_custom_shipping_method';
return $methods;
}
如果我让我的功能像这样:
function calculate_shipping( $pakage = array() ) {
$shipping_cost = 0;
$destination_district = $package["destination"]["city"];
switch($destination_district){
case 'Guaramirim': $shipping_cost = 5; break;
case 'Beta': $shipping_cost = 7; break;
}
$this->add_rate(array('id' => 'my_custom_shipping',
'label' => 'Taxa de Entrega',
'cost' => $shipping_cost,
'taxes' => '',
'calc_tax' => 'per_order'));
}
它与城市字段中的Guaramirim和Beta值配合得很好,但我不想使用任何默认字段,我需要使用自定义字段。