I'm trying to add a custom add to cart button to the product detail page that adds a separate/featured product to the cart. I'm using the following code to add the button for the product

<?php $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
  $postData = $postDataHelper->getPostData($_csData[0]['add_to_cart_url'], ['product' => $_csData[0]['product_id']]);
<button class="action tocart primary"
  data-post='<?= /* @escapeNotVerified */ $postData ?>'
  type="button" title="<?= /* @escapeNotVerified */ __('Add to Cart') ?>">
<span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>

I'm generating the add to cart url via \Magento\Catalog\Block\Product\ListProduct getAddToCartUrl()

The URL and form data look correct when compared to the data on the main product add to cart button. However, when I click the custom button, it say's adding and then displays a 'We can't find this product' error. I know the product exists, is enabled, has stock quantity, etc.

Has anyone run into this issue before? Could the issue lie in the form key? It's the same as the form key for the primary add to cart button. Do I need to generate a form key that is specific for my custom button? Any thoughts/suggestions would be appreciated.

  • Turns out that this code will work. Be sure that your template file has a .phtml extension and not .php. Once that error was found this worked as expected. – mlunt Jan 4 at 15:50

Your Answer

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

Browse other questions tagged or ask your own question.