
Magento 2.*: How to get add to cart button in a custom templete file
If you need to show the add to cart button in a custom template file, or in a block where it does not come by default (for example, related products block), you should do the following:
- Get the corresponding phtml file.
Note: By default, Magento uses the same template for product related, upsell, crosssel and new products content widget.
This template comes from vendor/magento/module-catalog/view/frontend/templates/product/list/items.phtml.
If we want to custom this template, we should copy it to our current theme: app/design/frontend/{Vendor Theme}/{Theme name}/Magento_Catalog/templates/product/list/items.phtml.
- Add the following code:
1234567891011121314<?php$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');$addToCartUrl = $listBlock->getAddToCartUrl($product);?><form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post"><?php echo $block->getBlockHtml('formkey')?><div class="btn"><button type="submit" title="Add to Cart" class="action tocart primary"><span>Add to Cart</span></button></div></form>
Bear in mind, that using the object manager is not a good practice, and you should avoid using it. If you have the chance to get the addToCart url by an item within the block you are using, or with a product object that you already have, it will be better.