0

I want to check whether a product exists within a specific category and if true show message.

At the moment I am having to do this via strpos using the Name attribute value.

   <?php if (strpos($_product->getName(),"Hello") !==false): ?>
    <div style="margin-bottom:10px;">
     <p><i style="font-style:italic;">A message goes here.</i></p>
    </div>
   <?php endif; ?>

Is there any way to do similar using either category name or ID?

1

2 Answers 2

1

Copy following code in your phtml file:

<?php $yourCatIds = array(1,2,3...);
$productCats = $_product->getAvailableInCategories();

if (count(array_intersect($yourCatIds,$productCats))) {
    echo '<li>' . $_product->getData('attributecode') . '</li>';
}
?>
1
  • Doesn't seem to work... does it matter that the category I am looking at is a parent category (i.e. the product is contained within child of a parent)? Commented Mar 17, 2021 at 16:02
0

You can check if your product belongs to a specific special category id :

<?php
$productCategoryIds = $product->getCategoryIds();
$specialCategoryId=3;

?>
    
<?php if (in_array($specialCategoryId,$productCategoryIds)): ?>
    <div style="margin-bottom:10px;">
     <p><i style="font-style:italic;">A message goes here.</i></p>
    </div>
<?php endif; ?>
2
  • Doesn't seem to work... does it matter that the category I am looking at is a parent category (i.e. the product is contained within child of a parent)? Commented Mar 17, 2021 at 16:02
  • The product has to be a member of the category you are testing for.
    – paj
    Commented Mar 17, 2021 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.