The “Buy now” button allows the user to skip the card page when buying a product and go directly to the checkout page and purchase the product faster.
In this tutorial, you will learn how to add a Buy Now button to your WooCommerce product page without a plugin. We will also see how to customize this button and place it only on products in certain categories.

buy now button for woocommerce

Add buy now button in WooCommerce without plugins

Using the following code, you can add the “Buy now” button to single and variable products in WooCommerce.

Buy now button WooCommerce code

In the WordPress dashboard, go to Appearance ➡ Theme File Editor and copy the following code into the theme’s functions.php file and save it.

You must create a child theme before making any changes to functions.php file. Otherwise, the applied changes will be lost after each update.
Create child theme in WordPress step by step [without plugin]

As an alternative method, you can use the Code Snippets plugin to insert your codes into WordPress.

/* buy now button woocommerce code by WPcookie
 * update: https://redpishi.com/wordpress-tutorials/buy-now-button-woocommerce/
 */
add_action('wp_footer', function() {
    if (!is_admin()) {
        // Change button color from here
        $color = "";
        ?>
        <style>
        a.custom-checkout-btn {
            margin: 0px 5px!important;
        }
        </style>
        <?php
        if ($color != "") {
            ?>
            <style>
            a.custom-checkout-btn {
                background: <?php echo $color; ?>!important;
                transition: 0.4s filter ease;
            }
            a.custom-checkout-btn:hover {
                filter: saturate(2);
            }
            </style>
            <?php
        }
    }
});

add_action('woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout');
function add_custom_addtocart_and_checkout() {
    global $product;

    // conditional tags
    $condition = $product->is_type('simple') || $product->is_type('variable');

    $button_class = 'single_add_to_cart_button button alt custom-checkout-btn';

    // Change the text of the buy now button from here
    $button_text = __("Buy now", "woocommerce");

    if ($condition) {
        // For both simple and variable products
        ?>
        <script>
        jQuery(function($) {
            var checkoutUrl = '<?php echo wc_get_checkout_url(); ?>',
                addToCartUrl = '<?php echo wc_get_cart_url(); ?>',
                qty = 'input.qty',
                button = 'a.custom-checkout-btn';

            function updateBuyNowButton() {
                var $form = $('form.cart'),
                    productId = $form.find('input[name="product_id"]').val(),
                    variationId = $form.find('input[name="variation_id"]').val(),
                    quantity = $form.find(qty).val();

                var targetUrl = checkoutUrl + '?add-to-cart=';
                
                if (variationId && variationId != '') {
                    targetUrl += variationId;
                } else {
                    targetUrl += productId;
                }

                targetUrl += '&quantity=' + quantity;

                // Add all selected attributes to the URL
                $form.find('.variations select').each(function() {
                    var attributeName = $(this).attr('name');
                    var attributeValue = $(this).val();
                    if (attributeValue) {
                        targetUrl += '&' + attributeName + '=' + attributeValue;
                    }
                });
                
                $(button).attr('href', targetUrl);
            }

            // Initial update
            updateBuyNowButton();

            // On quantity change
            $(qty).on('input change', updateBuyNowButton);

            // On variation change
            $('.variations_form').on('woocommerce_variation_has_changed', updateBuyNowButton);

            // Ensure button is updated after variation is selected
            $('form.variations_form').on('show_variation', function(event, variation) {
                updateBuyNowButton();
            });

            // Update on any attribute change
            $('.variations_form').on('change', 'select', updateBuyNowButton);

            // Disable the button if not all attributes are selected
            $('.variations_form').on('change', 'select', function() {
                var allSelected = true;
                $('.variations_form select').each(function() {
                    if ($(this).val() === '') {
                        allSelected = false;
                        return false;  // break the loop
                    }
                });
                
                if (allSelected) {
                    $(button).removeClass('disabled').attr('aria-disabled', 'false');
                } else {
                    $(button).addClass('disabled').attr('aria-disabled', 'true');
                }
            });

            // Prevent click if button is disabled
            $(button).on('click', function(e) {
                if ($(this).hasClass('disabled')) {
                    e.preventDefault();
                    alert('Please select all product options before purchasing.');
                }
            });
        });
        </script>
        <?php
        echo '<a href="#" class="' . $button_class . '">' . $button_text . '</a>';
    }
}

After adding the above code to the site theme’s “functions.php” file, you will see the “Buy now” button on the product pages.

Customize the “Buy now” button

Find the section below in the code and enter the desired color code to modify the “Buy now” button’s color.

// Change button color from here
$color = "#ff6a00"; 

To change the text of the “Buy now” button, find the following section of the code and replace “Buy now” with your desired wording.

// Change the text of the buy now button from here
$button_text   = __("Buy now", "woocommerce");

Add buy now to some categury

To display the “Buy Now” button on products from a specific category, Find the $condition variable and replace it with the conditional tag below.
In the code below, instead of ‘tshirts’, write the Slug of category you want.

// conditional tags
$condition = has_term( [ 'tshirts' ], 'product_cat' ) ;

From now on, the “buy now” button will only be displayed for T-shirts.
If you want more than one category, separate each category Slug with a comma.

// conditional tags
$condition = has_term( [ 'tshirts', 'hoodies', 'decor' ], 'product_cat' );

To learn more about conditional tags and how to use them in WordPress, read the following article.
https://redpishi.com/wordpress-tutorials/insert-code-in-wordpress-without-plugins/#insert-php-code-in-pages-with-given-terms

If this article is difficult for you to read in text, you can watch the video version below.

Share this post
Maya
Maya

Hi, my name is Maya and I’m a WordPress plugin developer. I created this website to share some of the helpful codes that I’ve used in my own projects.
If you’re looking for a custom plugin for your website, you can contact me by clicking on Hire a developer in the menu. I’d love to hear from you.

Articles: 56

13 Comments

  1. Hi! your code is amazing but I added to websites and everything its ok but in variable products text button change, text \”BUY NOW\” transform to add to cart automatically.
    can you help me?
    thanks

    • Try this code:

      add_action(\’woocommerce_after_add_to_cart_button\’, \’add_custom_addtocart_and_checkout\’);
      function add_custom_addtocart_and_checkout() {
      global $product;

      // conditional tags
      $condition = $product->is_type(\’simple\’) || $product->is_type(\’variable\’);

      $button_class = \’single_add_to_cart_button button alt custom-checkout-btn\’;

      // Change the text of the buy now button from here
      $button_text = __(\”Buy now\”, \”woocommerce\”);

      if ($condition) {
      ?>

      jQuery(function($) {
      var checkoutUrl = \’\’,
      addToCartUrl = \’\’,
      qty = \’input.qty\’,
      button = \’a.custom-checkout-btn\’;

      function updateBuyNowButton() {
      var $form = $(\’form.cart\’),
      productId = $form.find(\’input[name=\”product_id\”]\’).val(),
      variationId = $form.find(\’input[name=\”variation_id\”]\’).val(),
      quantity = $form.find(qty).val();

      var targetUrl = checkoutUrl + \’?add-to-cart=\’;

      if (variationId && variationId != \’\’) {
      targetUrl += variationId;
      } else {
      targetUrl += productId;
      }

      targetUrl += \’&quantity=\’ + quantity;

      $form.find(\’.variations select\’).each(function() {
      var attributeName = $(this).attr(\’name\’);
      var attributeValue = $(this).val();
      if (attributeValue) {
      targetUrl += \’&\’ + attributeName + \’=\’ + attributeValue;
      }
      });

      $(button).attr(\’href\’, targetUrl).text(\”\”);
      }

      updateBuyNowButton();

      $(qty).on(\’input change\’, updateBuyNowButton);
      $(\’.variations_form\’).on(\’woocommerce_variation_has_changed\’, updateBuyNowButton);
      $(\’form.variations_form\’).on(\’show_variation\’, function(event, variation) {
      updateBuyNowButton();
      });
      $(\’.variations_form\’).on(\’change\’, \’select\’, updateBuyNowButton);

      $(\’.variations_form\’).on(\’change\’, \’select\’, function() {
      var allSelected = true;
      $(\’.variations_form select\’).each(function() {
      if ($(this).val() === \’\’) {
      allSelected = false;
      return false;
      }
      });

      if (allSelected) {
      $(button).removeClass(\’disabled\’).attr(\’aria-disabled\’, \’false\’);
      } else {
      $(button).addClass(\’disabled\’).attr(\’aria-disabled\’, \’true\’);
      }
      });

      $(button).on(\’click\’, function(e) {
      if ($(this).hasClass(\’disabled\’)) {
      e.preventDefault();
      alert(\’Please select all product options before purchasing.\’);
      }
      });
      });

      <?php
      echo '\’ . $button_text . \’\’;
      }
      }

      In this version, $(button).attr(\’href\’, targetUrl).text(\”\”); ensures that the button text is always set to \”Buy Now\” each time the URL updates, even when WooCommerce tries to change it to \”Add to Cart\” on variable products. This should resolve the issue.

      • thanks, I see your reply today!
        but with this new code error syntax appear:

        syntax error, unexpected identifier \”button\” line 112:

        $button_class = ’single_add_to_cart_button button alt custom-checkout-btn’;

  2. Thanks a lot for this. But the buy now is still acting as add to cart. Instead of just redirecting to checkout page. It still adding to cart. Any help pls

  3. Hi there,

    Thanks so much for this! I would like to know how I can make the \”Buy now\” button a little smaller? I tried changing the margin px value from 5 to 4. I didn\’t notice any change in the size of the button though.

    Appreciate it!
    Albert

    • Hi Albert
      If you want to customize the size of the button, this code will do the trick:

      a.custom-checkout-btn {
      width: 80px;
      height: 20px;
      flex: unset;
      }

      • Thanks so much!
        I\’ve actually just managed to add a max height to the code 🙂
        I followed the same way the other lines were added and after a few tries, managed to get it right.

        I appreciate your fast reply!

  4. hi i have a problme with the code it s not the bouton but\’s it s not direct me to place order page directly my buton have the same fonction of add to cart button

  5. Hai, please help me on this. This code works perfectly fine for me, but I am facing one issue with the external or affiliated products. I don\’t want this Buy Now button on External Products as it return a message in the cart window saying \”This product cannot be purchased\” O how do I remove this button from external products?

    • Hey Dhanuan!
      Thanks a lot for your comment.
      I made some changes to the code, so now the Buy Now button will only show up for simple and variable products.

Leave a Reply

Your email address will not be published. Required fields are marked *