1

I've seen great examples all over the web of how to add custom tabs to product details, and I've successfully added tabs to my products. But any thoughts on how to only add a tab if a corresponding attribute exists for that particular product?

Thanks!

2

It's not difficult. First, set the attribute on layout file. Go to

app\design\frontend\Vendor\Theme\Magento_Catalog\layout\catalog_product_view.xml

and add your attribute:

<referenceBlock name="product.info.details">
    <block class="Magento\Catalog\Block\Product\View\Description" name="new_attribute" template="Magento_Catalog::product/view/attribute.phtml" group="detailed_info">
        <arguments>
            <argument name="at_call" xsi:type="string">getNewAttribute</argument>
            <argument name="at_code" xsi:type="string">new_attribute</argument>
            <argument name="css_class" xsi:type="string">new-attribute</argument>
            <argument name="at_label" xsi:type="string">new-attribute</argument>
            <argument name="add_attribute" xsi:type="string">itemprop="new-attribute"</argument>
            <argument name="title" translate="true" xsi:type="string">New Attribute</argument>
        </arguments>
    </block>
</referenceBlock>

That's all. You will ask why it can. The magic is inside

vendor/magento/module-catalog/view/frontend/templates/product/view/attribute.phtml

which is a core file. Here is the code from line 40(I'm using 2.2.6 as reference, maybe different on various version):

<?php if ($_attributeValue): ?>
<div class="product attribute <?= /* @escapeNotVerified */ $_className ?>">
    <?php if ($renderLabel): ?><strong class="type"><?= /* @escapeNotVerified */ $_attributeLabel ?></strong><?php endif; ?>
    <div class="value" <?= /* @escapeNotVerified */ $_attributeAddAttribute ?>><?= /* @escapeNotVerified */ $_attributeValue ?></div>
</div>
<?php endif; ?>

The statement <?php if ($_attributeValue): ?> will check whether you inserted values on that product attribute. So if the field is empty, the tab will NOT show.

  • 1
    Was definitely over-thinking it, should've just played around with it. Thanks a bunch. – brackfost Oct 11 '18 at 12:43

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.