Create a module by following steps:
- app/code/M2Expert/CmsAddtocart/registration.php
with below code:
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'M2Expert_CmsAddtocart', __DIR__ );
- app/code/M2Expert/CmsAddtocart/etc/module.xml
with below code:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="M2Expert_CmsAddtocart" setup_version="0.0.1"> <sequence> <module name="Magento_Backend"/> <module name="Magento_Sales"/> <module name="Magento_Quote"/> <module name="Magento_Checkout"/> <module name="Magento_Cms"/> <module name="Magento_Catalog"/> </sequence> </module> </config>
- app/code/M2Expert/CmsAddtocart/Block/CmsCart.php
with below code:
<?php namespace M2Expert\CmsAddtocart\Block; class CmsCart extends \Magento\Framework\View\Element\Template { protected $productRepository; protected $listProductBlock; protected $scopeConfig; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Catalog\Block\Product\ListProduct $listProductBlock, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig ) { $this->productRepository = $productRepository; $this->listProductBlock = $listProductBlock; $this->scopeConfig = $scopeConfig; parent::__construct($context); } public function getAddToCartUrl() { if ($_product = $this->getProduct()) { return $this->listProductBlock->getAddToCartPostParams($_product); } return '#'; } public function getProduct() { if ($product_id = $this->getProductId()) { $_product = $this->productRepository->getById($product_id); if ($_product) { return $_product; } } return false; } }
- app/code/M2Expert/CmsAddtocart/view/frontend/templates/cms/addtocart.phtml
with below code:
<?php $postParams = $block->getAddToCartUrl(); ?> <?php $buttonText = $block->getButtontext(); ?> <form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post"> <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>"> <input type="hidden" name="uenc" value="<?php /* @escapeNotVerified */ echo $postParams['data']['uenc']; ?>"> <?php echo $block->getBlockHtml('formkey')?> <button type="submit" title="Add to Cart" class="action tocart primary"> <span><?= ($buttonText)? $buttonText : __('Add to Cart') ?></span> </button> </form>
Done!!
You can now use that on cms page or cms block like below:
{{block class='M2Expert\CmsAddtocart\Block\CmsCart' product_id=2 buttontext="Add to Cart from CMS" template='M2Expert_CmsAddtocart::cms/addtocart.phtml'}}