wordpress 以编程方式将百分比增加到所有WooCommerce运费

rekjcdws  于 2023-06-21  发布在  WordPress
关注(0)|答案(2)|浏览(174)

我正试图增加65%的增加在所有运输方式。
我已经使用了这个函数的变体,但这并不影响返回的速率。

function increase_shipping_costs() {
  // Get the current shipping rates
  $shipping_zones = WC_Shipping_Zones::get_zones();

  foreach ( $shipping_zones as $zone ) {
    foreach ( $zone['shipping_methods'] as $shipping_method ) {
      // Check if the shipping method is a flat rate
      if ( !$shipping_method->id === 'free_shipping' ) {
        // Get the current cost
        $current_cost = $shipping_method->cost;

        // Calculate the increased cost
        $increased_cost = $current_cost + ( $current_cost * 0.65 );

        // Update the shipping cost
        $shipping_method->cost = $increased_cost;
        $shipping_method->save();
      }
    }
  }
}

add_filter('woocommerce_package_rates', 'increase_shipping_costs', 10, 2);
9cbw7uwe

9cbw7uwe1#

要在所有运输方式费率中增加65%的成本,woocommerce_package_rates是正确的过滤器钩子,但您需要修改函数中的大部分内容以使其正常工作 (因为代码中有一些遗漏和错误)

add_filter('woocommerce_package_rates', 'increase_shipping_costs', 10, 2);
function increase_shipping_costs( $rates, $package ) {
    $rate_multiplier = 1.65; //  65% increase cost
    
    // Loop through shipping rates
    foreach ( $rates as $rate_key => $rate ) {
        
        if ( 'free_shipping' !== $rate->method_id && $rate->cost > 0 ) {
            $has_taxes = false; // Initializing
            $taxes     = array(); // Initializing

            $rates[$rate_key]->cost = $rate->cost * $rate_multiplier; // Set new rate cost
            
            // Loop through taxes array (change taxes rate cost if enabled)
            foreach ($rate->taxes as $key => $tax){
                if( $tax > 0 ){
                    $taxes[$key] = $tax * $rate_multiplier; // Set the new tax cost in the array
                    $has_taxes   = true; // Enabling tax changes
                }
            }
            // set array of shipping tax cost
            if( $has_taxes ) {
                $rates[$rate_key]->taxes = $taxes;
            }
        }
    }
    // For a filter hook, always return the main argument
    return $rates; 
}

代码放在活动子主题(或活动主题)的functions.php文件中。应该能用

ktca8awb

ktca8awb2#

筛选器的回调设置不正确:

  • 缺少函数参数
  • 没有返回值(筛选器需要返回值)

您需要使用通过过滤器提供的数据(例如:$package_rates)而不是WC_Shipping_Zones::get_zones()

function increase_shipping_costs( $package_rates, $package ) {
    ...

    return $package_rates;
}
add_filter( 'woocommerce_package_rates', 'increase_shipping_costs', 10, 2 );

相关问题