Posted on 17th, January 2018

Getting the add to cart URL for a product.

Sometimes you’ll need to get the add to cart URL for a given product, to do this you’ll want to use the following helper class: Magento\Checkout\Helper\Cart, and the method: getAddUrl.

Below is a practical example of this being used:

<?php
namespace Namespace\Module\Block;

use \Magento\Framework\View\Element\Template;
use \Magento\Framework\View\Element\Template\Context;
use \Magento\Checkout\Helper\Cart as CartHelper;
use \Magento\Catalog\Api\ProductRepositoryInterface;

class MyBlock extends Template {

    protected $cartHelper;
    protected $productRepository;

    public function __construct(CartHelper $cartHelper, ProductRepositoryInterface $productRepository Context $context, array $data = []) 
    {
        $this->cartHelper = $cartHelper;
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    public function getAddToCartUrlForProduct($productSku)
    {
        $product = $this->productRepository->get($productSku);
        return $this->cartHelper->getAddUrl($product);
    }

}

Don’t forget that any similar examples using the ObjectManager are bad practise and should be avoided.

Final note: When you use this URL, make sure you submit it with a POST request, and that the request contains the form key too!

Ash Smith - Freelance Magento Developer

I'm Ash, a freelance Magento 2 Developer, keen cyclist and aspiring triathlete. With over eight years Magento experience, I have a wealth of experience with developing Magento stores.

Need a Magento Contractor/Freelancer? Contact me