这是我的自定义插件代码:
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();
我正在试图使用这个过滤器,但他不起作用。前端没有任何事情发生。我不知道错误在哪里。
这不是我应该使用过滤器吗?
答案 0 :(得分:1)
更新。
您的代码中存在一些错误,例如:
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送货设置并在相关送货区域中查看“统一费率”,禁用/保存并重新启用/保存相应的“统一费率”。