Magento – If Statement for Attribute and Category Conditions

ifproduct-view

I have a large amount of products, about half do not have a proper description. To address this I've created an if statement that will display the product name one way and if the condition is not met then it will display it another.

Example:

<?php if ($_product->getproduct_updated()) : ?>
<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?><?php echo $this->__(' ') ?>(<?php echo $_product->getData('mpn')?>)
<?php else: ?>
<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>
<?php else: ?>

Now, I'd like to go a step further with the above rule and set it so that if the product_updated attribute is yes AND is in certain categories, then display:

<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?><?php echo $this->__(' ') ?>(<?php echo $_product->getData('mpn')?>)<?php echo $this->__(' ') ?><?php echo $_helper->productAttribute($_product, nl2br($_product->getShortDescription()), 'short_description') ?>

I've done some searching and found some code and have tried for over an hour to get it to work:

<?php $categoryIds = $_product->getCategoryIds();?>
        <?php if ($_product->getproduct_updated()) && (count(array_intersect($categoryIds, array(2,71,101)))): ?>

How can I use 2 conditions in an if statement condition 1: yes/no condition 2: in categories 2,71,101 ?

Best Answer

What I would do is separate each check into variables so that it is slightly easier to read and then the check just becomes two boolean checks.

Firstly the simple one is the product updated, I will assume it returns a boolean already but please correct me if I am wrong ;)

$productUpdated = $_product->getProductUpdated();

Now the slightly trickier one. I would firstly take the categories out that you are matching against and then perform a array_intersect and a count > 0 so that you end up with a boolean here.

$categoryIdsToMatch = array(2,71,101);
$categoryMatched = count(array_intersect($categoryIds, $categoriesToMatch)) > 0;

Now your if becomes very simple just check that both cases match :)

if ($productUpdated && $categoryMatched)

Since this looks like it is in a template file my final suggestion would be to include all this into a block and so in the end you only call one function.

if ($this->checkUpdatedAndCategoryMatch())

In this function I would still keep the separation of the checks and in this way you should be able to maintain the code a bit more and other developers should be able to read it, to be honest I like to do it this way cause in a years time I wont remember but will have to fix my own mistakes ;)

Related Topic