Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respect product sort in Collections #10

Open
philipmarnef opened this issue Nov 2, 2021 · 1 comment
Open

Respect product sort in Collections #10

philipmarnef opened this issue Nov 2, 2021 · 1 comment

Comments

@philipmarnef
Copy link

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
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants