Sorting by price asc/desc using Structure as product variation

Hi People,
I’m crafting a Shop with Kirby and I’m stuck with something as simple as modifying the asc / desc order by price. Each product is a page and in it I have the product variations as a Structure with the color, size and price.
When there is more than one variation with different prices, the ideal would be to use the lowest price as a reference.
Anyone have any idea how I can change the sorting order by price in the product listing?
Normally it would be as simple as:

$products->sortBy('price', 'asc');

But having the price inside a structure I can’t think of how to do it, does anyone have any ideas?
If it helps, my Blueprint has a structure like:

            label: Product variations
            type: structure
            required: true
            translate: false
                label: Color
                type: text
                width: 1/2
                required: true
                label: Talla 
                type: select
                width: 1/2
                    t12: 12
                    t14: 14
                    t18: 18
                label: Price
                type: number
                required: true
                before: €
                width: 1/2

Many thanks!

sortBy() accepts a callback function:

$sorted = $products->sortBy(function($element) {
  $lowestPriceElement = $element->variations()->toStructure()->sortBy('price', 'asc')->first();
  return $lowestPriceElement->price();
}, 'desc');

Not tested.

You should add and additional check if the $lowestPriceElement exists before calling the price method, of course.

1 Like

It’s working like a charm!
Thanks @texnixe :smiley: