[Magento] Listing sub-categories on a category page
Tutorial này sẽ hướng dẫn các bạn cho hiển thị danh sách sub-category bao gồm ảnh thumbnails và tên của subcategories trong trang category.
Bước 1: Đăng nhập vào admin: CMS -> Static Blocks -> Add New Block
Bước 2: Gọi block này vào nội dung static block -> save.
{{block type=”catalog/navigation” template=”catalog/navigation/subcategory_listing.phtml”}}
Bước 3: Catalog –> Manage Categories Chọn vào 1 category bất kì có subcategory chọn vào tab Display Settings Tab. Add static block vừa tạo ở trên vào category này ->save.
Bước 4: Tạo file block phtml : subcategory_listing.phtml được gọi trong static: theo đường dẫnapp/design/frontend/default/MY-TEMPLATE/template/catalog/navigation/ với nội dung sau
- < ?php
$_categories=$this->getCurrentChildCategories();
< ?php echo $this->htmlEscape($_category->getName()) ?>
if($_categories->count()):
$categorycount = 0;
foreach ($_categories as $_category):
if($_category->getIsActive()):
$cur_category=Mage::getModel('catalog/category')->load($_category->getId());
$layer = Mage::getSingleton('catalog/layer');
$layer->setCurrentCategory($cur_category);
$catName = $this->getCurrentCategory()->getName();
if ($categorycount == 0){
$class = "first";
}
elseif ($categorycount == 3){
$class = "last";
}
else{
$class = "";
}
?>
< ?php endif; if($categorycount == 3){ $categorycount = 0; echo "
\n\n
- ";
}
else{
$categorycount++;
}
endforeach;
endif;
?>
Bước 5: override block Navigation.php bằng cách coppyapp\code\core\Mage\Catalog\Block\Navigation.php sangapp\code\local\Mage\Catalog\Block\Navigation.php
Tìm tới funtion :
public function getCurrentChildCategories()
Và replace nội dung function này với nội dung sau:
public function getCurrentChildCategories()
{
$layer = Mage::getSingleton('catalog/layer');
$category = $layer->getCurrentCategory();
/* @var $category Mage_Catalog_Model_Category */
$collection = Mage::getModel('catalog/category')->getCollection();
/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
$collection->addAttributeToSelect('url_key')
->addAttributeToSelect('name')
->addAttributeToSelect('is_anchor')
->addAttributeToSelect('image')
->addAttributeToFilter('is_active', 1)
->addIdFilter($category->getChildren())
->setOrder('position', 'ASC')
->joinUrlRewrite()
->load();
$productCollection = Mage::getResourceModel('catalog/product_collection');
$layer->prepareProductCollection($productCollection);
$productCollection->addCountToCategories($collection);
return $collection;
}
Sau khi hoàn thành xóa cache và chạy thử xem kết quả: