How to setup a Drupal Commerce Order total Range condition

Auteur(s) de l'article

The other day, I faced a serious problem. One of our clients wanted a new shipping methods that must be applied on Ranged Order Total Price condition.
AKA a shipping method that must apply only when the order total falls within a range. E.g. $100 => order total <= $200.
After digging the Drupal Commerce Issue Queue, I found out there is no out-of-the-box solution/patch (for now) to apply an Order Total Price within a range Condition. So let's code it !
This is what you will be able to achieve at the end of this story
Truth can only be found in one place: the code

Robert C. Martin

Clean Code: A Handbook of Agile Software Craftsmanship

The Plugin Condition

For the most curious ones, here is a unit test Class that you may be interested to add on your project to ensure plugin stability:
Well done you did it !

Shia LaBeouf

That's pretty much all the hocus-pocus that you need to have custom Commerce Total Price Order Condition fitting within a range.

Going Further

The code upper here is simplified.
Still, you may want to change the code in order to exclude adjustments or change the in between operators used.
Total price includes adjustments
You may want to remove the adjustments (taxes, shipping, etc ...) in order to trigger the condition.
Then update the OrderTotalPriceRange::evalute method.
// (...)

if (!$total_price) {
  return FALSE;

// Subtract tax & shipping adjustments.
$adjustments = $order->collectAdjustments(array_filter(['tax', 'shipping']));
foreach ($adjustments as $adjustment) {
  $total_price = $total_price->subtract($adjustment->getAmount());

// (...)
Configurable between operators
The given plugin use a hardcoded “Between” condition including the input values (>= && <=).
You can still change this condition by updating the return condition of OrderTotalPriceRange::evalute.
return $total_price->greaterThan($condition_price_from)
      && $total_price->lessThan($condition_price_to);


Many thanks to Quentin Fahrner for sharing with me an inital Plugin solution.


For the most curious of you, here are some sources of additional information that inspired the creation of this article.
Quentin Fahrner (11 May, 2022). Order total range condition.
See on