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
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>';
}
?>
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)? – YorkieMagento Mar 17 at 16:02
  • +1 for using array_intersect !! – paj Mar 17 at 16:28
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)? – YorkieMagento Mar 17 at 16:02
  • The product has to be a member of the category you are testing for. – paj Mar 17 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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