At app/design/frontend/Custom/Theme/Magento_Catalog/templates/product/list.phtml I'm trying to apply a javascript for certain products (not all of them) as follows:

<?php foreach ($_productCollection as $_product): ?>
    <?php if ($_product->getData('custom_attribute')): ?>
        //some javascript that apply for the products that contain the attribute
    <?php endif; ?>
<?php endforeach; ?>

What would be the best approach to achieve this in a way that the Magento good practices are guaranteed. Thanks for your input and collaborations


Your question is not specific, but I can try to answer:

  1. Turn on flat tables for products.
  2. Add new attribute (just like in your question) and make sure that "used in product listing" is set to Yes. Type should be Boolean. (That's crucial - your newly created attribute values will be stored inside flat table).
  3. Add changes in list.phtml (for example like in your question).

There won't be any additional db queries to run (if you setup attribute just like I suggest in 2.) to get your values and it will only add one little column to Magento collection query with boolean values.

There are more places to add your code (.phtml files), but you can easily find them inside layout .xml file.

| improve this answer | |
  • Hii; i was thinking about executing some javascript inside the if statement; i know it is not a good practice to place the javascript inside the if statement, so i was then wondering what the best approach would be. The attribute has been defined already, so getData checks if the products have already the attribute – Julian Murillo Feb 7 '19 at 7:01

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.