skip to Main Content

I would like to add a list of categories to my conditional statement, how should I add multiple categories id ?
Using like 123,124,125 or 123 || 124

I have a big list of categories so I am looking for the cleanest way to achieve that

thanks

<?php
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->get('MagentoFrameworkRegistry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/
foreach($categories as $category){
    $cat = $objectManager->create('MagentoCatalogModelCategory')->load($category);
    echo $cat->getId();
    }

?>

  <?php if($cat->getId()==123): ?>
    <?php echo $block->getLayout()->createBlock('MagentoCmsBlockBlock')->setBlockId('myblockid')->toHtml();?>
    <?php endif; ?>

3

Answers


  1. Use in_array PHP function:

    <?php if(in_array($cat->getId(), [123, 124, 125])): ?>
    
    Login or Signup to reply.
  2. The best solution is to use in_array function

    <?php
       if(in_array($cat->getId(), $your_array){
          $block->getLayout()->createBlock('MagentoCmsBlockBlock')->setBlockId('myblockid')->toHtml();
       }
    ?>
    
    Login or Signup to reply.
  3. Use in_array() : This Checks if a value exists in an array or not.Return true if exist.

    <?php
        if(in_array($cat->getId(), $categories ):
            echo $block->getLayout()->createBlock('MagentoCmsBlockBlock')->setBlockId('myblockid')->toHtml();
        endif;
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search