0
votes

There is the built in option for woocommerce shipping to set a fee for quantity of products in cart. There is also option for fee per shipping class. But I have thousands of products and need to charge a fee for each product(each product not qty of products).

For example 2 product "apples", and 23 product "oranges" in cart. I need to charge flat fee of $10 for any amount of apples and $10 for any amount of oranges. I dont seem to find solution to this in any of the available plugins. They all do fee per quantity but not this.

1

1 Answers

2
votes

To get a cost by line item in cart, it requires the following:

1) In WooCommerce Settings > Shipping: set a cost of 10 for your "Flat rate" shipping methods (and save).

2) Add to functions.php file of your active child theme (or active theme), this code:

add_filter( 'woocommerce_package_rates', 'shipping_cost_based_on_number_of_items', 10, 2 );
function shipping_cost_based_on_number_of_items( $rates, $package ) {
    $numer_of_items = (int) sizeof($package['contents']);

    // Loop through shipping rates
    foreach ( $rates as $rate_key => $rate ){
        // Targetting "Flat rate" shipping method
        if( 'flat_rate' === $rate->method_id ) {
            $has_taxes = false;

            // Set the new cost
            $rates[$rate_key]->cost = $rate->cost * $numer_of_items;

            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_key]->taxes as $key => $tax){
                if( $tax > 0 ){
                    // New tax calculated cost
                    $taxes[$key] = $tax * $numer_of_items;
                    $has_taxes = true;
                }
            }
            // Set new taxes cost
            if( $has_taxes )
                $rates[$rate_key]->taxes = $taxes;
        }
    }
    return $rates;
}

Refresh the shipping caches: (required)

  1. This code is already saved on your active theme's function.php file.
  2. The cart is empty
  3. In a shipping zone settings, disable / save any shipping method, then enable back / save.

Tested and work.