Magento – Set filter to layered navigation programmatically

filterable-attributeslayered-navigationmagento-1.9

Using below code i'm getting list of filterable attributes

$layer = Mage::getModel("catalog/layer");
$attributes = $layer->getFilterableAttributes();

I can't able to set filters and get it's sub filters. example i have below 2 filterable attributes,

Size
 28 (1)
 30 (2)

Color
 Green (2)
 Red (1)

On selecting Size 28, my sub filter is

Color
 Red (1)

So i'm trying to achieve below,

  • Get all available attribute filters initially (got this using getFilterableAttributes())

  • Set filter programatically and get it's sub filters as like above example

Best Answer

To set some "initial" filters you can rewrite the app\code\core\Mage\Catalog\Model\Layer.php class and adjust the product collection in the method getProductCollection:

    $collection = parent::getProductCollection();
    $db = Mage::getSingleton('core/resource')->getConnection('core_read');
    $tableAlias = 'amasty_example';
    $conditions = array(
        "{$tableAlias}.entity_id = e.entity_id",
        $db->quoteInto("{$tableAlias}.attribute_id = ?", 198),
        $db->quoteInto("{$tableAlias}.store_id = ?", $collection->getStoreId()),
        $db->quoteInto("{$tableAlias}.value = ?", 67)
    );

    $collection->getSelect()->join(
        array($tableAlias => Mage::getSingleton('core/resource')->getTableName('catalog/product_index_eav')),
        implode(' AND ', $conditions),
        array()
    );

the code above is based on app\code\core\Mage\Catalog\Model\Resource\Layer\Filter\Attribute.php