Zend certified PHP/Magento developer

Magento2.4: How to sort products by Size options (XS, S , M, L ,XL)?

I want to sort Products based by their size like (extra small, small, medium, large) you can take Magento reference what they use for this term,)

  • 1: Products with All Size options should be on top.

you can see below query as refrence.

SELECT sl.parent_id, COUNT(sl.product_id), SUM(IFNULL(ss.stock_status, 0)) FROM catalog_product_super_link as sl
  INNER JOIN catalog_product_entity as p ON sl.parent_id = p.entity_id
  INNER JOIN catalog_product_entity as c ON sl.product_id = c.entity_id
  LEFT JOIN cataloginventory_stock_status as ss ON ss.website_id = 0 AND c.entity_id = ss.product_id
GROUP BY sl.parent_id;

and i want this query to implement in this peace of code.

<?php

namespace VendorModuleModelVisualMerchandiserSorting;

use MagentoCatalogModelResourceModelProductCollection;
use MagentoVisualMerchandiserModelSortingSortAbstract;
use MagentoVisualMerchandiserModelSortingSortInterface;

class AllSizeTop extends SortAbstract implements SortInterface
{
    /**
     * @param Collection $collection
     * @return Collection
     */
    public function sort(
        Collection $collection
    ): Collection {
        .
        // your logic
        .
        return $collection;
    }

    /**
     * @return string
     */
    public function getLabel(): string
    {
        return __("All Size to Top");
    }
}

Means Products with most size options ( can be max 5,6,7) should be on top and vice versa and products with size 1 or no size option should be bottom

  • 2: i also want to sorting options like
  • products with 5 options canbe on top
  • products with 4 options can be on top

from below link you can take an idea of what i wanna do. any idea, Thanks in advance. How to add Sort options in back-end grid as shown in pictures?

How to add Sort options in back-end grid as shown in pictures?