I'm looking to add 5 products add to cart buttons to a CMS page in Magento 2, the code example I found online is:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
$addToCartUrl =  $listBlock->getAddToCartUrl($product);

Where $product is an ID passed to the phtml file from my CMS page, however the above code seems to just gives a white screen and I don't get anything logged in my system or exception files that indicates what's happening.

How would I retrieve the product's add to cart URL in a phtml file from the product ID?


Try this :

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

$productHelper = $objectManager->get('\Magento\Catalog\Model\Product');
$_product = $productHelper->load($product)

$listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
$addToCartUrl =  $listBlock->getAddToCartUrl($_product);
| improve this answer | |
  • This works in so far as I get the url - but doesn't add anything to the cart. Do I need to add the form key? – Aravona Nov 3 '16 at 12:35
  • How would I add that to this url? – Aravona Nov 3 '16 at 12:37
  • I'm not using a hidden field but a direct URL, so how would that work? – Aravona Nov 3 '16 at 12:44
  • @Aravona after url you can use : $URL.'/qty/1/form_key/'.$block->getFormKey() – Ashish Jagnani Nov 3 '16 at 12:51
  • Yes but how do I get said formkey? – Aravona Nov 3 '16 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.