cancel
Showing results for 
Search instead for 
Did you mean: 

Show HTML only if product is in certain category

Show HTML only if product is in certain category

Hi,

 

I would like to display certain html on the product page only if the product is (also) in category id 350.
The product is in many categories. I don't want to show the html when the product is viewed necessarily from a specific category path.
So someone can visit the product page on domain.com/productURL without getting there from a specific category.
What's important is that if that product is ALSO (not only) in category id 350, among other categories its in, than show a certain div.

I'm tying to put an if statement in a phtml file that is already set up, but I don't seem to get the if statement right.

This is not something suitable to do in the backend - only in my custom phtml file.

I would really appreciate if anyone knows how to achieve this.

 

Thanks!

3 REPLIES 3

Re: Show HTML only if product is in certain category

Should be simple enough if you only want to show it to the customer if they come via category 350 on catalog/product/view.phtml template

 

<?php
$catid = Mage::registry('current_category') ? Mage::registry('current_category')->getId() : null;

if($catid == 350):?>
<div class"of 2002">
You found me
</div>

<?php endif; ?>

Re: Show HTML only if product is in certain category

Alternatively, if this is to be displayed IF in category 350 regardless

 

 <?php
 $currentCatIds = $_product->getCategoryIds();
if (in_array("350", $currentCatIds )):
?>
<div class="of 2002"> 
You found the missing lemon
</div>
<?php endif;?>

Re: Show HTML only if product is in certain category

Get the current category using object manager

 

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentCategory = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category information
$c_cat_id = $currentCategory->getId();

if($c_cat_id != 439):
//do something
endif;