Mo Boho Mo Boho - 3 months ago 10
PHP Question

Magento: List product categories EXCEPT a select few

I am looking to list on the product page the categories that a particular product belongs to; HOWEVER, I would like to be able to say do NOT list some specific categories.

A solution to outputting the list of categories a product belonged to was posted by a fellow stackoverflow user here: http://stackoverflow.com/a/9720480/99112 and it works great to output the results. How could the above code be modified to get what we are looking for?

Just to draw up an example of what I mean:

Say a Product A is a member of Category IDs: 4, 7, 9, 14, 92

On the product page, I want to output the names of the above categories MINUS category IDs: 7, 92
So, the output would only be Category ID names for: 4, 9, 14

The categories we would want to exempt would apply to all products. So in the above example and looking at a Product B, it would also output Category ID names EXCEPT for the ones we don't want (i.e. 7, 92).

Here is the code in question from the above thread (thanks to user "Sarath Tomy"):

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


How would we modify this to check a list of Category IDs that we do NOT want outputted, please?
Many thanks.

Answer

Here's a solution that worked (no idea if it's the most efficient way of doing it or not), but here it is:

  <?php $categories = $_product->getCategoryIds(); ?>
  <?php foreach($categories as $k => $_category_id): ?>
  <?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?>
  <?php if (!in_array($_category->getId(), array(XX,YY))) : ?>
    <a href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a>
  <?php endif; ?>
  <?php endforeach; ?>

where you put in whatever Category IDs you want to exclude in place of XX,YY above.