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:

    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.