Reputation: 651
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: https://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.
Upvotes: 0
Views: 887
Reputation: 651
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.
Upvotes: 1
Reputation: 9910
You could make a System - Configuration
setting that contains a multiple select with all the categories.
The categories selected would be the ones excluded.
Now, the best practice would be to extend Mage_Catalog_Model_Product
, and add another method getVisibleCategoryIds()
Here's how it would look (not tested):
public function getVisibleCategoryIds() {
return array_diff($this->getCategoryIds(), Mage::getStoreConfig('section_name/group/field'));
}
Or you can extend getCategoryIds()
directly and save the hassle of modifying through templates. This would look like this:
public function getCategoryIds() {
return array_diff(parent::getCategoryIds(), Mage::getStoreConfig('section_name/group/field'));
}
Upvotes: 0