Magento – Add to cart url do not work

addtocartmagento2

I have generated an add to cart url on the frontend, but it do not seem to work. When I click on the link, I get the "You have no items in your shopping cart." page.

I have got this add to cart url from Magento: http://test.com/magento2/checkout/cart/add/uenc/aHR0cDovL2xvY2FsaG9zdC9tYWdlbnRvMi8,/product/7/

And here is the code how I created the url:

$id = 7; 

$om = \Magento\Framework\App\ObjectManager::getInstance();

$productHelper = $om->get('\Magento\Catalog\Model\Product');

$cartHelper = $om->get('\Magento\Checkout\Helper\Cart');

echo $cartHelper->getAddUrl($productHelper->load($id));

Best Answer

Use below code:

$id = 7; 

$om = \Magento\Framework\App\ObjectManager::getInstance();

$productHelper = $om->get('\Magento\Catalog\Model\Product');

$listBlock = $om->get('\Magento\Catalog\Block\Product\ListProduct');

echo $listBlock->getAddToCartUrl($productHelper->load($id));

It helpful to you.

Related Topic