Enhance the user experience on your WooCommerce store by providing customers with a quick and direct option to purchase products. With a “Buy Now” button added to the single product page, customers can bypass the cart and proceed straight to checkout, streamlining the purchasing process.
/**
* Snippet Name: Add "Buy Now" button to single product page
* Snippet Author: wpsnippets.dev
*/
// Add "Buy Now" button to single product page
function wps_add_buy_now_button() {
global $product;
// Check if the product type is 'simple'
if ( ! $product->is_type( 'simple' ) ) {
return; // Only show on simple products
}
// Output "Buy Now" button with product's direct checkout link
echo '<a href="' . esc_url( '/checkout?add-to-cart=' . $product->get_id() ) . '" class="button">Buy Now</a>';
}
add_action( 'woocommerce_after_add_to_cart_form', 'wps_add_buy_now_button', 10 );
Code Explanation
- This snippet adds a “Buy Now” button to the single product page of WooCommerce using the woocommerce_after_add_to_cart_form hook. It’s placed just below the product’s Add to Cart button.
- Inside the callback function add_buy_now_button(), we first check if the product type is “simple” using the is_type() method. The button will only be displayed if the product type is simple.
- Next, we construct the URL for the button’s link using the product’s ID and the /checkout?add-to-cart= endpoint. This URL ensures that the product is directly added to the cart and redirects the user to the checkout page.
- Finally, we output the “Buy Now” button with the constructed URL as the link.