1. Home
  2. Help Center
  3. WooCommerce
  4. Customization
  5. Add a “Buy Now” button

To create a simple Buy Now button that adds a product to cart and redirects to checkout use the following code snippets.

This is the PHP code. Add the code to /wp-content/themes/goya-child/functions.php:

add_filter('woocommerce_add_to_cart_redirect', 'add_redirect_to_checkout'); function add_redirect_to_checkout($redirect_url) { if (isset($_REQUEST['is_buy_now']) && $_REQUEST['is_buy_now']) { global $woocommerce; $redirect_url = wc_get_checkout_url(); if ( !is_product() ) { wc_clear_notices(); } } return $redirect_url; } add_action('woocommerce_after_add_to_cart_button', 'add_buy_now_button', 1); function add_buy_now_button() { global $product; ?> <div class="buy-now-container-single-product yith-wcwl-add-to-wishlist"> <div> <button type="submit" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>" class="single_add_to_cart_button single_buy_now_button ywgc-add-gift-product-to-cart button alt" id="buy_now_button"> <?php echo esc_html('Buy Now'); ?> </button> <input type="hidden" name="is_buy_now" id="is_buy_now" value="0" /> </div> </div> <?php } add_action('woocommerce_after_add_to_cart_form', 'buy_now_submit_form'); function buy_now_submit_form() { ?> <script> jQuery(document).ready(function(){ jQuery('#buy_now_button').click(function(){ jQuery('#is_buy_now').val('1'); jQuery('#buy_now_button').parents('form.cart').submit(); }); }); </script> <?php }
Code language: JavaScript (javascript)

Then, add this CSS code either to Appearance > Customize > Additional CSS or /wp-content/themes/goya-child/style.css:

.single_buy_now_button { width: 100%; margin-top: 10px; }
Code language: CSS (css)

Use the same class .single_buy_now_button to customize the Buy Now button styles.

Was this article helpful?

Related Articles