Magento获取指定分类下的产品和获取子分类及产品数量
Magento首页及分类页面侧边栏经常需要调用某一个分类下的产品,例如首页的Featured Product等。这些分类一般保持不激活状态,我们可以添加店铺中比较畅销的产品到该分类中,并从前台调用。下面一段代码主要用处就是在Magento中获取指定分类下的产品。
|
$products = Mage::getModel( 'catalog/category' )->load( $category_id ) ->getProductCollection() ->addAttributeToSelect( '*' ) ->addAttributeToFilter( 'status' , 1) ->addAttributeToFilter( 'visibility' , 4); |
将上面的$category_id修改为需要显示产品的分类id,该id可以在分类页面中看到。上述代码中还捎带了一些过滤,产品状态为激活,并处于可见状态。
很多Magento的项目中,客户需求将每个当前分类下的每个子分类以及该分类下的产品数量全部显示出来,类似于Category (108)的形式。如下所示
Magento
- Magento 模板 (4)
- Magento 插件 (2)
想实现这种效果,就必须要知道如何获取当前分类的子分类,并了解Product Collection类中的count()方法。该方法用于获取任意形式下对于Product Collection进行筛选后的产品数量。
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
|
// 获取当前分类模型 $currCat = Mage::registry( 'current_category' ); //获取当前分类的所有子分类的模型集合 $collection = Mage::getModel( 'catalog/category' )->getCategories( $currCat ->getEntityId()); //循环子分类的模型集合 foreach ( $collection as $cat ) { if ( $cat ->getIsActive()) { $category = Mage::getModel( 'catalog/category' )->load( $cat ->getEntityId()); //获取子分类的产品Collection,并通过count()方法,获取该子分类的产品数量 $prodCollection = Mage::getResourceModel( 'catalog/product_collection' )->addCategoryFilter( $category ); Mage::getSingleton( 'catalog/product_status' )->addVisibleFilterToCollection( $prodCollection ); Mage::getSingleton( 'catalog/product_visibility' )->addVisibleInCatalogFilterToCollection( $prodCollection ); $html .= '<a href="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?></a> (<?php echo $prodCollection->count() ?>)<br/>' ; } } |