How to get Add to Cart button on phtml Magento 2
In Magento 2, the “Add to Cart” button plays a crucial role in the e-commerce shopping experience. It allows customers to conveniently add products to their shopping carts. By default, Magento provides this button on product detail pages, but there may be instances where you need to add it to a custom PHTML file. In this blog post, we will explore the steps to add the “Add to Cart” button on a PHTML file in Magento 2.
Add the “Add to Cart” Button on the PHTML File in Magento 2
Within the PHTML file, find the appropriate location to insert the “Add to Cart” button.
To create the “Add to Cart” button, use the following code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
$productSku = 'SKU-01';
$product = $productRepository->get($productSku);
$productId = $product->getId();
$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
$addToCartUrl = $listBlock->getAddToCartUrl($product);
$postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($product), ['product' => $productId]);
?>
<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>
You can replace the value of $productSku with a fixed SKU value, or you can getSku() from the current product or from the product list.
Once completed, to ensure the changes take effect, save the file and clear the Magento cache. You can do this by running the following command in the terminal:
php bin/magento cache:clean
Conclusion
Adding the “Add to Cart” button to a PHTML file in Magento 2 is a simple yet powerful customization that can greatly enhance the shopping experience on your online store. By following the step-by-step instructions provided in this blog post, you can create unique shopping experiences tailored to your specific business needs. Whether you want to display the button in a prominent position alongside product information, within a custom-designed section, or even on pages beyond the default product detail pages, Magento 2 offers the flexibility to achieve your desired layout.
Remember to thoroughly test the changes you make to ensure that the “Add to Cart” button functions correctly and that it harmonizes with the overall design and responsiveness of your website. Pay attention to factors such as compatibility across different devices and browser types to ensure a seamless shopping experience for all customers.