简体   繁体   中英

Magento - Conditionally Display Attribute Based on Product Category

I am trying to display an attribute ('release') if a product has a certain category ID. This is what I have so far:

<?php $category = Mage::getModel('catalog/layer')->getCurrentCategory();?>
<?php if($category->getId() == 2): ?>
<h5 style="color:#f26522" >
<?php echo $_product->getData('release') ?></h5>
<?php else: ?>

This works well, but only allows me to limit to products categorized under the default category, in this case 'Id() == 2'.

I am trying to limit the function to display only for a subcategory of this root category, but it does not respond to its corresponding category ID.

How can this be accomplished? All help is appreciated!

For reference: Conditional loading content based on category id magento for product page

Edit for Solution:

<?php
  $categoryIds = $_product->getCategoryIds();
  if(in_array(20,$categoryIds)):
?>
<h5 style="color:#f26522" ><b>
<?php echo $_product->getData('release'); ?></h5></b>
<?php endif;    ?>

Thanks to @RS and @ndlinh for their input and support.

Special thanks to @programmer_rkt whose response here helped clarify this concept.

For Further Reference: Changing Display According to Product Category

Take a look @ Magento category ID from product ID

$product = Mage::registry('current_product');
if ($product->getId()) {
    $categoryIds = $product->getCategoryIds();
    if (is_array($categoryIds) && in_array(2 , $categoryIds)
      ...
      echo $_product->getData('release')
      ...

Assuming that you are on the product detail page

Here is my solution:

<?php 
    $category = Mage::getModel('catalog/layer')->getCurrentCategory();
    $parentIds = $category->getParentIds();
?>
<?php if(in_array(2, $parentIds): ?>
    <h5 style="color:#f26522" >
    <?php echo $_product->getData('release') ?></h5>
<?php else: ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM