我使用自定义插件的商业运输方式。该插件运行一个新类,该类扩展了WC_Shipping_方法,但问题是“成本”价格是在类外的其他函数中计算的。
因此,在当前课程中,我有:
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,则不会更新签出页面上的运费:
公共函数calculate\u 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函数之前运行,这就是为什么它不能获得$提取变量的值。
如何解决这个问题?
在计算运输成本的函数中,添加一个带有新计算值的会话变量,如下所示:
//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可以更新我的发货价值。。。我仍然在寻找解决方案,虽然。。。lol:)
$("#billing_address_1").trigger("keypress").val(function(i,val){return val + 'a';});