tristantbg / kirby-shopify

MIT License
61 stars 7 forks source link

Respect product sort in Collections #10

Open philipmarnef opened 3 years ago

philipmarnef commented 3 years ago

Currently products in a collection are sorted alphabetically, since that's how $shopify->Product->get(['collection_id' => $collectionId]) returns them in getProductsFromCollection() and there's no way to sort the returned results.

After digging deeper I found there's also $shopify->Collection($collectionId)->Product->get() which returns a list of all products in the collection in their preferred sort order. Unfortunately those product objects don't contain the variant property and they're not filtered for inventory.

So what I did is pull the $shopify->Collection($collectionId) list to get the sort order, then sort the $products list based on that:

$products = self::$shopify->Product->get(['limit' => 250, 'published_status' => 'published', 'status' => 'active', 'collection_id' => $collectionId]);

// Patch: sort products by order in collection
$collection = self::$shopify->Collection($collectionId)->Product->get();
$sort = [];
foreach($collection as $key => $product) {
  $sort[$product['id']] = $key;
}

usort($products, function($a, $b) use ($sort) {
  return $sort[$a['id']] - $sort[$b['id']];
});

I'm hesitating to make a pull request because I'm unsure if this is the most effective way to do this and it's also untested (yet). Would welcome a discussion around this.

On a side note: I was also wondering what the fallback code in while (count($products) < $productsCount) is for, since I don't understand how these could differ?

tristantbg commented 3 years ago

Hi @philipmarnef Thank you for investigating into this.

The best solution would be to switch the whole code to use GraphQL instead and get the right order directly. If you solution work, don't hesitate to create a pull request I can review.

About the while loop, this one is necessary to take care of the Shopify pagination limit which is 250 items per request.

Best