phpmagento2advanced-search

Magento 2 Advance Search sort by category


I want to display advanced search products with sort of category position, but I don't know which event I need to invoke for this.


Solution

  • Here is the code to sort products by categories position.

    $this->_productCollection->getSelect()
        ->joinLeft(
            ['category' => 'catalog_category_product', 'cp' => 'catalog_category_entity'], 
            'e.entity_id = category.product_id',
            ['category.category_id']
        )
        ->joinLeft(
            ['cp' => 'catalog_category_entity'],
            'category.category_id = cp.entity_id',
            ['cp.position']
        )->group('e.entity_id');
    
    $this->_productCollection->getSelect()->order(
        'cp.position ' . $this->getCurrentDirectionReverse()
    );