Woocommerce运输计算器的自定义字段



我正在为Wooccommerce构建一种自定义运输方法,我完全不知道如何将自定义值传递给calculate_shipping()函数,无论是在Cart页面还是Checkout页面上使用它。

我需要传递一些用户定义的变量,这些变量将影响报价,例如"是住宅地址"、"是贸易展"等。

calculate_shipping接收$package数组,该数组包含一个"destination"数组,但这只包括标准的add1、add2、城市、州、邮政编码、国家信息。我已经在结账页面的账单和运费下添加了自定义字段,但我仍然不知道如何让calculate_shipping函数访问这些值。

我添加了一个自定义字段:

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['shipping']['is_residential'] = array(
'label'     => __('Residential Address?', 'woocommerce'),
'type'      => 'checkbox',
'required'  => false,
'class'     => array('form-row-wide'),
'clear'     => true
);
return $fields;
}

我看到这个字段显示在结账表的"发货"部分。但是,我不知道如何在任何地方访问它。即使在结账页面上执行print_r($_POST),也不会将此字段显示为发布数据的一部分,即使在我知道表单已经更新并重新发布之后也是如此。

但最重要的是,我需要将提交字段的内容添加到$package对象中,Wooccommerce将其传递给运输方法的calculate_shipping()函数。

我真的不知道从哪里开始。

您不能期望添加签出字段并在购物车页面上提供这些字段。

正确的方法是使用购物车包裹。

从class-wc-cart.php 检查function get_shipping_packages()

public function get_shipping_packages() {
// Packages array for storing 'carts'
$packages = array();
$packages[0]['contents']                 = $this->get_cart();       // Items in the package
$packages[0]['contents_cost']            = 0;                       // Cost of items in the package, set below
$packages[0]['applied_coupons']          = $this->applied_coupons;
$packages[0]['destination']['country']   = WC()->customer->get_shipping_country();
$packages[0]['destination']['state']     = WC()->customer->get_shipping_state();
$packages[0]['destination']['postcode']  = WC()->customer->get_shipping_postcode();
$packages[0]['destination']['city']      = WC()->customer->get_shipping_city();
$packages[0]['destination']['address']   = WC()->customer->get_shipping_address();
$packages[0]['destination']['address_2'] = WC()->customer->get_shipping_address_2();
foreach ( $this->get_cart() as $item )
if ( $item['data']->needs_shipping() )
if ( isset( $item['line_total'] ) )
$packages[0]['contents_cost'] += $item['line_total'];
return apply_filters( 'woocommerce_cart_shipping_packages', $packages );
}

您必须挂接到woocommerce_cart_shipping_packages过滤器并在那里添加字段。

很可能您需要在发货计算器和结账页面添加它们(您的字段)。

希望这能有所帮助。

最新更新