I need to add possibility in Layered Navigation to filter by two categories. Can you give me a hint what should I change?
1 Answer
Since nobody answer my question, I post my solution. It's working as I wanted, but I am not shure if it's good enough, so please correct me, if there is better solution.
So when I on category page I already have first category id in 'id' parameter and also I pass another GET parameter 'cat' with second category id.
First I extended Mage_Catalog_CategoryController where I save my category ids to the Registry
include_once("Mage/Catalog/controllers/CategoryController.php");
class My_CustomModule_Catalog_CategoryController extends Mage_Catalog_CategoryController
{
protected function _initCatagory()
{
$categoryId = (int) $this->getRequest()->getParam('id', false);
Mage::register('first_category', $categoryId);
$cat_param = (int) $this->getRequest()->getParam('cat', false);
if($cat_param) Mage::register('second_category', $cat_param);
return parent::_initCatagory();
}
}
Then I use catalog_product_collection_apply_limitations_after event for calling function addDoubleCategoriesHandle() from my Observer.php. Here I replace original join "cat_index" part - with two "joins" for both of my categories. And dont forget to replace cat_index on cat_index2 in second "joinCondition" to avoid sql errors.
class My_CustomModule_Model_Observer {
public function addDoubleCategoriesHandle(Varien_Event_Observer $observer) {
$collection = $observer->getEvent()->getCollection();
$fromPart = $collection->getSelect()->getPart(Zend_Db_Select::FROM);
if (isset($fromPart['cat_index']) && (Mage::registry('first_category')) && (Mage::registry('second_category'))) {
$pattern = "/cat_index.category_id = '\d+'/";
$replacement = "(cat_index.category_id = '".Mage::registry('first_category')."')";
$first_cat_join = preg_replace($pattern, $replacement, $fromPart['cat_index']['joinCondition']);
$replacement2 = "(cat_index2.category_id = '".Mage::registry('second_category')."')";
$second_cat_join = preg_replace($pattern, $replacement2, $fromPart['cat_index']['joinCondition']);
$second_cat_join = str_replace('cat_index.','cat_index2.',$second_cat_join);
$fromPart['cat_index']['joinCondition'] = $first_cat_join;
$fromPart['cat_index2'] = $fromPart['cat_index'];
$fromPart['cat_index2']['joinCondition'] = $second_cat_join;
$collection->getSelect()->setPart(Zend_Db_Select::FROM, $fromPart);
}
}
}