Skip to content

Magento2.4.2: How to sort product collection by sub category as shown in this picture?

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
enter image description here

and i’m following this approach

VendorModuleModelVisualMerchandiserSortingSummerCollection.php

<?php
declare(strict_types=1);
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace VendorModuleModelVisualMerchandiserSorting;

use Exception;
use MagentoCatalogModelProductAttributeSourceStatus;
use MagentoCatalogModelProductVisibility;
use MagentoCatalogModelResourceModelProductCollection;
use MagentoFrameworkDataCollection as CollectionAlias;
use MagentoVisualMerchandiserModelSortingSortAbstract;
use MagentoVisualMerchandiserModelSortingSortInterface;

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');
    }
}