Is there a way to add a 'Add to Cart and Checkout' button to the product page, so that the product is added to the cart and then takes the user straight to the checkout?
Magento 2 – Checkout Button on Product Page
checkoutjquerymagento2product
checkoutjquerymagento2product
Is there a way to add a 'Add to Cart and Checkout' button to the product page, so that the product is added to the cart and then takes the user straight to the checkout?
Best Answer
By default, Magento used Ajax in product page. When pressing the add to cart button, the data will be sent to
vendor/magento/module-checkout/Controller/Cart/Add.php
. I have two suggestions for you.Navigate to
vendor/magento/module-catalog/view/frontend/web/js/catalog-add-to-cart.js
, we can seeajaxSubmit
function which will handle the response data from the server. It will check the back Url that it will redirect to if this url exists.And then, go to the cart controller
vendor/magento/module-checkout/Controller/Cart/Add.php
. Inexecute()
method, if a product is added to cart successfully, Magento will call agoBack
method to resolve the response data.As can we see, the back url will get the url value from
$backUrl
argument or$this->getBackUrl()
. If we set one, Magento will redirect to it. So, basically, we have two ways to redirect to checkout page.1. We may rewrite the
execute()
method and add a back url(this way not recommend). For example:2. We add a return url in the product page template, should rewrite also (easier way). For example, add a return url inside the product view form.
More advanced, Magento has a config STORES > Configuration > SALES > Checkout > Shopping Cart > After Adding a Product Redirect to Shopping Cart. We can follow the logic of this option to build our own redirect.