I want to sort products by sub category as seen in this picture like Sort by Summer Collection as Muzlin summer 20 or Sort by winter collection
and i'm following this approach
Vendor\Module\Model\VisualMerchandiser\Sorting\SummerCollection.php
<?php
declare(strict_types=1);
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Vendor\Module\Model\VisualMerchandiser\Sorting;
use Exception;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Framework\Data\Collection as CollectionAlias;
use Magento\VisualMerchandiser\Model\Sorting\SortAbstract;
use Magento\VisualMerchandiser\Model\Sorting\SortInterface;
class SummerCollection extends SortAbstract implements SortInterface
{
/**
* @inheritDoc
* @throws Exception
*/
public function sort(Collection $collection): Collection
{
$catIds=[];
$categoriesId=[];
foreach ($collection as $product)
{
$categoriesId[]= $product->getCategoryIds();
$catIds=array_merge($catIds, $categoriesId);
}
$finalCat = array_unique($catIds);
$collection->getSelect()->order(new \Zend_Db_Expr('FIELD(category_id,' . implode(',', $finalCat).')'));
return $collection;
}
/**
* @inheritDoc
*/
public function getLabel()
{
return __('Summer Collection Wise Sorting');
}
}