skip to Main Content

So I’m using this code to display the categories that any product on my website is included in. The issue is that I’m using some categories as placeholders to show ‘featured products’ I wanted to try to filter these out.

This is Magento 1.9.1.0 on PHP 5.6.30

<ul class="listfix">
<?php $categories = $_product->getCategoryIds(); ?>
<?php foreach($categories as $k => $_category_id):
 ?>
<?php $_category= Mage::getModel('catalog/category')->load($_category_id)?>
     <?php if($_category->getId()):?> 
    <li><a href="<?php echo $_category->getUrl() ?>"><?php echo $_category-
>getName() ?></a>
    </li>
        <?php endif;?>
   <?php endforeach; ?>
</ul> 

I tried adding this

    $_category->addAttributeToFilter('is_active', 1)//get only active 
    categories

but it threw an error, I’m not a great php guy, I just find pieces of code and try to make them work. I got the original parts from HERE

as per below I’ve tried to add in the code that follows but I’m still seeing categories listed that are not active…

<ul class="listfix">
<?php $activeCategories = 
Mage::getResourceModel('catalog/category_collection')
->addAttributeToFilter('is_active', 1)
->getColumnValues('entity_id');
?>  

<?php $activeCategories = $_product->getCategoryIds(); ?>
<?php foreach($activeCategories as $k => $_category_id):  ?>
<?php $_category= Mage::getModel('catalog/category')->load($_category_id)?>
    <?php if($_category->getId()):?> 
<li><a href="<?php echo $_category->getUrl() ?>"><?php echo $_category-
>getName() ?></a>
</li>
    <?php endif;?>

2

Answers


  1. Chosen as BEST ANSWER
    <ul class="listmem">
    <?php $activeCategories = 
    Mage::getResourceModel('catalog/category_collection')
    ->addAttributeToFilter('is_active', 1)
    ->getColumnValues('entity_id');?>
    
    <ul class="listfix">
    <?php $activeCategories = $_product->getCategoryIds(); ?>
    <?php foreach($activeCategories as $id) {
        $cat = Mage::getModel('catalog/category')->load($id);
    } ?>
    
    <?php if($cat->getId()):?> 
        <li><a href="<?php echo $cat->getUrl() ?>"><?php echo $cat->getName() ?>
    </a>
        </li>
    <?php endif;?>
    </ul> 
    

    I thought I sorted out what I was doing wrong, but I'm still seeing the categories that aren't active in my list.


  2. This will give you a list of all the active Categor ID’s in 1.9:

    $activeCategories = Mage::getResourceModel('catalog/category_collection')
    ->addAttributeToFilter('is_active', 1)
    ->getColumnValues('entity_id');
    

    Then you loop through that array, and load the category, or whatever, by ID:

    foreach($activeCategories as $id) {
      $cat = Mage::getModel('catalog/category')->load($id);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search