Adding extra cost to woocommerce flat rate based on shipping zone

To adjust the WooCommerce code so it adds an extra specific amount based on the shipping zone, you can modify the existing function to include shipping zone-based costs. Here’s a streamlined version of the code:

add_filter( 'woocommerce_package_rates', 'add_cost_based_on_zone_and_quantity', 10, 2 );

function add_cost_based_on_zone_and_quantity( $rates, $package ) {
    $shipping_class = "very-light-weight";  // Define the shipping class
    $qty_step = 20;  // Quantity threshold for a step
    $item_count = 0;  // Initialize item count

    // Define extra costs by shipping zone ID
    $zone_costs = array(
        'zone_1' => 50,  // Adjust these with actual zone IDs and costs
        'zone_2' => 75,
    );

    // Get the shipping class ID and count items
    $class_id = get_term_by('slug', $shipping_class, 'product_shipping_class')->term_id;
    foreach ($package['contents'] as $cart_item) {
        if ($cart_item['data']->get_shipping_class_id() == $class_id) {
            $item_count += $cart_item['quantity'];
        }
    }

    // Calculate the rate per quantity step
    $rate_operand = ceil($item_count / $qty_step);

    // Determine the shipping zone and retrieve additional costs
    $shipping_zone = WC_Shipping_Zones::get_zone_matching_package($package);
    $zone_id = $shipping_zone->get_id();  // Get zone ID

    foreach ($rates as $rate_key => $rate) {
        if ('flat_rate' === $rate->method_id) {
            $extra_cost = isset($zone_costs['zone_' . $zone_id]) ? $zone_costs['zone_' . $zone_id] : 0;
            $rates[$rate_key]->cost = ($rate->cost * $rate_operand) + $extra_cost;  // Adjust the total cost
        }
    }

    return $rates;
}

Key Adjustments:

  • Zone Costs Array: Contains additional costs linked to specific shipping zones.
  • Shipping Zone Detection: Identifies the customer’s shipping zone to determine extra charges.
  • Cost Adjustment: Modifies the shipping cost based on both item quantity and shipping zone.

Replace 'zone_1', 'zone_2' with your actual shipping zone identifiers and adjust the additional costs accordingly. This code now succinctly adds specific costs based on both the quantity of items and the customer’s shipping zone.

error code: 523