我使用自定义插件进行Woocommerce送货方式。该插件运行一个新类,它扩展了WC_Shipping_MEthod,但问题是“成本”价格是在该类外部的其他函数中计算的。
所以在目前的课程中我有:
public function calculate_shipping( $package=array() ) {
/* $this->add_rate( array(
'id' => $this->id . $this->instance_id,
'label' => $this->title,
'cost' => 0,
) ); */
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => 0,
'taxes' =>false,
//'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
}
在课外,在另一个档案中,我有一个功能,它计算运费:
//add shipping cost to checkout total
add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');
function woo_add_cart_fee() {
global $woocommerce;
$woocommerce->shipping;
$wc_econt = new WC_Econt_Shipping_Method;
if ( is_checkout() && (bool)$wc_econt->inc_shipping_cost == TRUE ) {
if(!isset($_SESSION)){
session_start();
}
//write_log('session econt customer shipping cost:'.$_SESSION['econt_shipping_cost']);
$extracost = (isset($_SESSION['econt_shipping_cost']) ? $_SESSION['econt_shipping_cost'] : 0 );
if ($extracost != '0') {
WC()->cart->add_fee(__('Econt Express Shipping Method','woocommerce-econt'), $extracost);
}
}
}
如果只在类功能中将0更改为$ extracode,则不会更新结帐页面上的运费:
public function calculate_shipping($ package = array()){
/* $this->add_rate( array(
'id' => $this->id . $this->instance_id,
'label' => $this->title,
'cost' => $extracost,
) ); */
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => $extracost,
'taxes' =>false,
//'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
}
我猜这个类在woo_add_cart_fee函数之前运行,这就是为什么它无法获得$ extracost变量的值。
如何解决这个问题?
答案 0 :(得分:0)
在计算运费的函数中,使用新的计算值添加会话变量,如下所示:
//add shipping cost to checkout total
add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');
function woo_add_cart_fee() {
global $woocommerce;
$woocommerce->shipping;
$wc_econt = new WC_Econt_Shipping_Method;
if ( is_checkout() && (bool)$wc_econt->inc_shipping_cost == TRUE ) {
if(!isset($_SESSION)){
session_start();
}
//write_log('session econt customer shipping cost:'.$_SESSION['econt_shipping_cost']);
$extracost = (isset($_SESSION['econt_shipping_cost']) ? $_SESSION['econt_shipping_cost'] : 0 );
if ($extracost != '0') {
WC()->session->set( 'Econt_Express_Shipping_Method' , $extracost );
}
}
}
然后在计算运费函数上使用WC会话变量来设置成本的值,如下所示:
public function calculate_shipping( $package=array() ) {
/* $this->add_rate( array(
'id' => $this->id . $this->instance_id,
'label' => $this->title,
'cost' => 0,
) ); */
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => WC()->session->get('Econt_Express_Shipping_Method' ),
'taxes' =>false,
//'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
}
使用以下javascript在结帐时更新新的运费值:
$('body').trigger('update_checkout', { update_shipping_method: true });
如果您在结帐时多次使用上述代码,则可能需要更改结算地址或送货地址或国家/地区的值,以便能够更新您的值。这也是我卡住的地方,我被迫伪造这些变化,以便Woocommerce可以更新我的运输价值......我仍在寻找解决方案虽然...大声笑:)
$("#billing_address_1").trigger("keypress").val(function(i,val){return val + 'a';});