Reputation: 565
How to get all products given a category name?
This is how i get all products given a category id
$cat_id = 1; // category id
$_productCollection = $product->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array('in' => array($cat_id)) )
->addAttributeToFilter('visibility', 4) // Only catalog, search visiblity
->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
->setCurPage(1)
->setPageSize(12);
but how do you get by category name?
Upvotes: 0
Views: 1803
Reputation: 2809
You can get category id from name by using following code
$cat = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', 'cat_name')->getData();
$cat_id = $cat[0]['entity_id'];
Now, use $cat_id
in product collection to get products filtered by category id
Upvotes: 2
Reputation: 1058
you can filter by name instead of id after joining the field category_name. replacing category_id by category_name should do the trick.
/**
* Join regular table field and use an attribute as fk
*
* Examples:
* (‘country_name’, ‘directory/country_name’, ‘name’, ‘country_id=shipping_country’, “{{table}}.language_code=’en’”, ‘left’)
*
* @param string $alias ‘country_name’
* @param string $table ‘directory/country_name’
* @param string $field ‘name’
* @param string $bind ‘PK(country_id)=FK(shipping_country_id)’
* @param string|array $cond “{{table}}.language_code=’en’” OR array(‘language_code’=>’en’)
* @param string $joinType ‘left’
* @return Mage_Eav_Model_Entity_Collection_Abstract
*/
joinField($alias, $table, $field, $bind, $cond=null, $joinType=’inner’)
and filter by category_name instead...
$cat_name = "catname"; // category id
$_productCollection = $product->getCollection()
->joinField('category_name', 'catalog/category_product', 'category_name', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_name', array('in' => array($cat_name)) )
->addAttributeToFilter('visibility', 4) // Only catalog, search visiblity
->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
->setCurPage(1)
->setPageSize(12);
Upvotes: 0
Reputation: 427
You want category id from category name right? so, u can use it further. try below. $cat = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', 'Category_Name_Here'); $cat->getFirstItem()->getEntityId();
Upvotes: 0