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/>'
;
}
}
|