Magento 2 – How to Show/Hide Custom Tab on Product Detail Page

custom-attributescustomtabmagento2product-attribute

I have created a product attribute like, display_custom_tab, if it is yes then show custom tab on product detail page, otherwise do not show tab.

can anyone please tell me how to write condition in xml or any other way to check condition.

Note : ifconfig will not work here, because product attributes are not stored in 'core_config_data'.

So, I have attributes like,
enter image description here

and tab like this,enter image description here

but tab is always showing on page. I want that if attribute is set to off, tab should hide.

This is my xml to show custom tab.

   <referenceBlock name="product.info.details">
        <block class="Magento\Catalog\Block\Product\View"
               name="warrantyInfo.tab"
               template="Product_CustomTab::custom_tab.phtml"
               group="detailed_info">
               <!--ifconfig="product/is_warranty_display"-->
            <arguments>
                <argument name="sort_order" xsi:type="string">40</argument>
                <argument translate="true" name="title" xsi:type="string">Warranty Info</argument>
            </arguments>
        </block>
    </referenceBlock>

Best Answer

Please make your code same as below code

In this example i have warranty_display attribute code for Warranty Display and warranty_info attribute code for Warranty Info.

Your catalog_product_view.xml code should be

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product.info.details">
            <block class="Magento\Catalog\Block\Product\View"
                   name="warrantyInfo.tab"
                   template="Product_CustomTab::custom_tab.phtml"
                   group="detailed_info">
                   <!--ifconfig="product/is_warranty_display"-->
                <arguments>
                    <argument name="sort_order" xsi:type="string">40</argument>
                    <argument translate="true" name="title" xsi:type="string">Warranty Info</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

your custom_tab.phtml file code should be

<?php if($this->getProduct()->getWarrantyDisplay()): ?>
    <?php echo $this->getProduct()->getWarrantyInfo(); ?>
<?php endif; ?>

When attribute enabled:

enter image description here

enter image description here

When attribute disabled:

enter image description here

enter image description here

Make sure you can get your attribute code in custom_tab.phtml file.

Hope this will help you!