add_filter WooCommerce运输的自定义插件文件中的问题



这是我的自定义插件代码:

class Class_name
{
public function __construct()
{
if ( is_admin() ) {
//Custom admin menu
add_action( 'admin_menu', array( $this,'custom_submenu_page'));

add_filter( 'woocommerce_package_rates', array($this , 'conditional_shipping', 10, 2 ));
}
}
function conditional_shipping( $rates, $packages ) {
if ( isset( $rates['flat_rate:32'] ) ) {
// Set the cost to $100
$rates['flat_rate:32']->cost = 100;
}
return $rates;
}

}

new Class_name();

我正在尝试使用这个过滤器,但他不起作用。前端什么也没发生。我不知道错误在哪里。

不是我应该使用过滤器吗?

运输方式的税收计算相关的更新。

代码中存在一些错误,例如:

add_filter( 'woocommerce_package_rates', array( $this , 'conditional_shipping', 10, 2 ) );

。这应该是:

add_filter( 'woocommerce_package_rates', array( $this , 'conditional_shipping' ), 10, 2 );

或者在代码末尾:

new Class_name();

。这应该是:

$GLOBALS['class_name'] = new Class_name();

所以你应该尝试这样完整的代码(之前清空购物车):

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if ( ! class_exists( 'Class_Name' ) ) {
class Class_Name {
public function __construct() {
//Custom admin menu
add_action( 'admin_menu', array( $this,'custom_submenu_page'));

add_filter( 'woocommerce_package_rates', array( $this , 'conditional_shipping' ), 10, 2 );
}
public function conditional_shipping( $rates, $package ) {
// HERE Defined Method rate ID
$rate_key = 'flat_rate:32';

// HERE Define New cost
$new_cost = 100;

## -- 1. Set the rate cost -- ##
if ( isset( $rates[$rate_key] ) ){
// Get original cost
$original_cost = $rates[$rate_key]->cost;
// Set the new cost
$rates[$rate_key]->cost = number_format($new_cost, 2);
// calculate the conversion rate (for taxes)
$conversion_rate = $new_cost / $original_cost;
}

## -- 2. Taxes rate cost calculation (if enabled) -- ##

$taxes = array();
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $tax > 0 ){
// set the new line tax cost in the array
$taxes[$key] = number_format($tax * $conversion_rate, 2);
}
}
// Set the new taxes costs
$rates[$rate_key]->taxes = $taxes;

## -- Return new costs -- ##
return $rates;
}
}
$GLOBALS['class_name'] = new Class_Name();
}

此代码位于插件文件中。它经过测试并工作。

您可能需要更新配送方式

转到WooCommerce运输设置,然后在"统一费率"的相关运输区域中,禁用/保存并重新启用/保存相应的"统一费率"。

最新更新