Monday, Jul 18, 2022 / Magento / Surbhi Patel

How to Create a Custom Buy Now Button in Magento 2

How to add a “Buy Now” button without using an extension in Magento

This module adds a “BuyNow” button on product view page and list page to process directly checkout.

Step-1 :

Copy below code & add to your Block File




namespace Krishaweb\ModuleName\Block;

class Index extends \Magento\Framework\View\Element\Template


    protected $categoryFactory;

    public function __construct(

        \Magento\Framework\View\Element\Template\Context $context,

        \Magento\Catalog\Model\CategoryFactory $categoryFactory,        

        \Magento\Catalog\Block\Product\ListProduct $listProductBlock,

        array $data = []

    ) {

        $this->categoryFactory = $categoryFactory;

        $this->listProductBlock = $listProductBlock;

        parent::__construct($context, $data);


    public function getAddToCartPostParams($product)


        Return $this->listProductBlock->getAddToCartPostParams($product);




Copy below code to add Buy Now button

(Add this code in your phtml file)


<?php $checkoutParams = $block->getAddToCartPostParams($product); ?>

<form data-role=”tocart-form” action=”<?php /* @escapeNotVerified */ echo $checkoutParams[‘action’]; ?>” method=”post”>

<?php echo $block->getBlockHtml(‘formkey’)?>

<input type=”hidden” name=”buynow” value=”yes”>

    <button type=”submit”

            title=”<?php echo $block->escapeHtml(__(‘Buy Now’)); ?>”

            class=”action tocart primary”>

            <span><?php /* @escapeNotVerified */ echo __(‘Buy Now’) ?></span>




Here We can use the preference to override or rewrite the controller.



<?xml version=”1.0″?>

<config xmlns:xsi=”” xsi:noNamespaceSchemaLocation=”urn:magento:framework:ObjectManager/etc/config.xsd”>

<preference for=”Magento\Checkout\Controller\Cart\Add” type=”Krishaweb\ModuleName\Controller\Cart\Add” />



Copy below code & add this code to your Controller in line no 126.



$buyNowButton  = $this->getRequest()->getParam(‘buynow’);

if ($buyNowButton) {

    $baseUrl = $this->_url->getBaseUrl();

    return $this->goBack($baseUrl . ‘checkout/’, $product);


Run Below commands


php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy

php bin/magento cache:flush


If this response is helpful to you, consider giving kudos to this post. Voila and it’s done. Please let us know if there is anything we missed. Waiting for your comments. Stay tuned.

Surbhi Patel
under Magento

You have a visionWe know the way to get you there.