只有Magento类别的有效产品才有效

时间:2013-05-31 13:36:16

标签: php magento magento-1.7

我正在尝试显示每个类别中的产品数量,使用此代码我想显示类别id:3的子类别。它显示但它包括残疾和隐形产品。

<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
?>
<ul>
<?php foreach($cats as $category): ?>
<li>
<a href="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?>(<?php echo $category->getProductCount(); ?>)</a>
</li>
<?php endforeach; ?>
</ul>

是否有任何好的解决方案,以便我可以获得启用和激活的类别的确切数量。

3 个答案:

答案 0 :(得分:3)

you need check active filter acondition and for this you can use below code 


    $products = Mage::getModel('catalog/category')->load($category->getId())
        ->getProductCollection()
        ->addAttributeToSelect('entity_id')
        ->addAttributeToFilter('status', 1)
        ->addAttributeToFilter('visibility', 4);

    echo $products->count();

答案 1 :(得分:1)

不考虑Magento编程约定,这段代码应如下所示:

<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
$collection = Mage::getModel('catalog/product')->getCollection();
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
?>
<ul>
<?php foreach($cats as $category): ?>
<?php $count = $collection->addCategoryFilter($category)->getSize(); ?>
<li>
<a href="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?>(<?php echo $count ?>)</a>
</li>
<?php endforeach; ?>
</ul>

但请帮助世界并正确组织代码。

答案 2 :(得分:0)

加载集合并使用多个属性过滤器不是一种正确的方法,这不会过滤关联的产品及其库存水平。

这段代码一起做,

$categoryId = 32; // Replace with your category

$category = Mage::getModel('catalog/category')
                 ->setStoreId(Mage::app()->getStore()->getId())
                 ->load($categoryId);
Mage::register('current_category', $category);

$products = Mage::getSingleton('catalog/layer')->getProductCollection();

echo $products->getSize();