0

I am using a headless magento 2 approach for my store. I have made an API which accepts parameters like:

category_slug, sort_by, sort_order, page_size, current_page

and returns the products matching the criteria.

Now the issue I am facing is, I want the out of stock products to be pushed down at the end of the ENTIRE collection.

My code is below:

$categoryProducts = $productFactory->create()
                        ->addAttributeToSelect('*')
                        ->addCategoriesFilter(array('in' => $categoryList))
                        ->addAttributeToFilter('status',1)
                        ->addAttributeToFilter('visibility',4)
                        ->addAttributeToSort($sort_by, $sort_order)
                        ->addAttributeToSort('is_in_stock', 'DESC')
                        ->setPageSize($page_size)
                        ->setCurPage($current_page)
                        ->load();

is_in_stock is a custom attribute I created which automatically gets set to 0 or 1 (0 being out of stock and 1 being in-stock), whenever a change in stock is detected (did this using an observer, working fine).

Now, suppose I want to sort the collection on PRICE, in ASC order the collection I am getting after this would look something like:

In-stock items of 10$, Out of stock items of 10$, In-stock items of 15$, Out of stock items of 15$, in stock items of 20$, and so on...

But what I want is:

In-stock items of 10$, In-stock items of 15$, in stock items of 20$, Out of stock items of 10$, Out of stock items of 15$, and so on...

I feel it's something really small and stupid that I am missing. any help would be appreciated.

Thanks!

1 Answer 1

0

I'm assuming here that ->addAttributeToSort($sort_by, $sort_order) is your price sort.

Sounds like you just need to swap your sort conditions. Since currently you will get is sorted by PRICE first, then STOCK.

So instead of

->addAttributeToSort($sort_by, $sort_order)
->addAttributeToSort('is_in_stock', 'DESC')

Change the order to

->addAttributeToSort('is_in_stock', 'DESC')
->addAttributeToSort($sort_by, $sort_order)

Now you'll first get all in-stock items, sorted by your second condition (price). Followed by all out-of-stock items, sorted by -again- your second condition (price).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.