Magento2 – How to Add a Custom Button to Product Page

magento2

I want to add a custom button beside the "Add to Cart" button in product page, the button I can add custom link, any help or suggestions would be greatly appreciated!

Best Answer

Copy the below file:

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

to your theme like below:

app/design/frontend/[Vendor]/[theme]/Magento_Catalog/templates/product/view/addtocart.phtml

and add the below code:

<div class="actions">
    <button type="submit"
            title="<?= /* @escapeNotVerified */ $buttonTitle ?>"
            class="action primary tocart"
            id="product-addtocart-button">
        <span><?= /* @escapeNotVerified */ $buttonTitle ?></span>
    </button>
    <?= $block->getChildHtml('', true) ?>
    <a class="primary action" href="<?= $_product->getCustomLink() ?>"><?= __('Custom Button') ?></a>
</div>

instead of:

<div class="actions">
    <button type="submit"
            title="<?= /* @escapeNotVerified */ $buttonTitle ?>"
            class="action primary tocart"
            id="product-addtocart-button">
        <span><?= /* @escapeNotVerified */ $buttonTitle ?></span>
    </button>
    <?= $block->getChildHtml('', true) ?>
</div>

I have just added the line:

<a class="primary action" href="<?= $_product->getCustomLink() ?>"><?= __('Custom Button') ?></a>

after:

<?= $block->getChildHtml('', true) ?>

In my case link attribute is custom_link. You need to replace it according to your attribute.

Related Topic