i want to default sort the products in product listing page by price in ascending order but zero price products should be at the end
product 1 : price 5$;
product 2: price 13$;
product 3 : price 0$;
product 4 : price 0$;
I understand the requirement you are trying to achieve for that i would suggest you to use below code :
$collection->addAttributeToSort('price', 'ASC');
On your listing page when you are trying to fetch product collection at that time use above code to filter your collection by Price and use ASC (Ascending) as filter parameter.
It will gives you collection according the way you want.
Hope it helps !
Well you can skip those values by adding addAttributetoFilter where price not eq to 0
But it will skip those values from the collection.
If you still wants those range at the end of the collection then you will require to use MySql query + collection by combining you can achieve the same.
Hope it helps !
Use following code to achieve the same :
$collection = $this->productFactory->create(); $collection->addAttributeToFilter('price', array('neq' => 0)); $collection->addAttributeToSort('price', 'ASC');
Hope it helps !
Hi Manthan..
its not work..
this is how i load products in product listing page in magento
$_productCollection = $block->getLoadedProductCollection();
By adding your code.. my products with the price zero is not showing.. i want to show them at the end.. how can i acheive it?
True - Didn't get a change to write query for this !
By above code your zero price product will not showcase may be you can add second collection or will post query once i get a time.
Hope it helps !