gpt4 book ai didi

wordpress - 用于运费计算器的 Woocommerce 自定义字段

转载 作者:行者123 更新时间:2023-12-03 06:50:14 24 4
gpt4 key购买 nike

我正在为 Woocommerce 构建自定义送货方法,而我完全困惑的一件事是如何将自定义值传递给calculate_shipping() 函数,无论是在购物车页面还是结帐页面上使用它时.

我需要传递一些会影响报价的用户定义变量 - 即“是住宅地址”、“是贸易展览”等。

calculate_shipping 接收包含“目的地”数组的 $package 数组,但这仅包含标准的 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 对象中,Woocommerce 会将该对象传递给运输方法的calculate_shipping() 函数。

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

最佳答案

您不能期望添加结帐字段并在购物车页面上提供它们。

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

检查function get_shipping_packages()来自类-wc-cart.php

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在那里过滤并添加您的字段。

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

希望这有帮助。

关于wordpress - 用于运费计算器的 Woocommerce 自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21790663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com