I have a Magento 2.2.9 based website and a cms page created that called in a phtml file.
In that phtml file, I am wanting to have an add to cart button for a specific product. However, clicking the button does not seem to add the item to my cart. I am wondering if anyone could suggest changes tome code get it to work.
<?php
$sku ='KACI01';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
$product = $productRepository->get($sku);
$productid = $product->getId();
$cartHelper = $this->helper('Magento\Checkout\Helper\Cart');
$addToCartUrl = $cartHelper->getAddUrl($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')?>
<button class="action tocart primary" data-post='<?php echo $postData; ?>' type="button" title="Add to Bag">
<span>Add to Bag</span>
</button>
</form>