Add a "Buy Now" Button Next to Add to Cart
Adds a second button on product pages that adds the product to the cart and takes the shopper straight to checkout, while the normal add to cart button keeps working.
Opens WPIDE on
Code
add_action( 'woocommerce_after_add_to_cart_button', function () {
global $product;
if ( ! $product instanceof WC_Product || ! $product->is_purchasable() || ! $product->is_in_stock() || $product->is_type( array( 'external', 'grouped' ) ) ) {
return;
}
echo '<button type="submit" name="wpide_buy_now" value="1" class="button alt wpide-buy-now" style="margin-left:8px;">' . esc_html( 'Buy now' ) . '</button>';
if ( $product->is_type( 'simple' ) ) {
printf( '<input type="hidden" name="add-to-cart" value="%d">', (int) $product->get_id() );
}
} );
add_filter( 'woocommerce_add_to_cart_redirect', function ( $url ) {
if ( ! empty( $_REQUEST['wpide_buy_now'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
return wc_get_checkout_url();
}
return $url;
}, 20 );
Notes
Works for simple and variable products on the classic product template.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.