[PHP] Buy Now button for WooCommerce product page

This is simple script to add Buy Now button below the Add To Cart button. After press this button, customer will be redirect to checkout page with select product.

Please add this snippet below to your functions.php file into your theme. Or you can install Code Snippets plugin then add new one and paste snippet below.

<?php
add_action( 'woocommerce_after_add_to_cart_button', 'salesgen_buynow_button_php', 99 );
function salesgen_buynow_button_php() {
	if ( !is_single() ) {
		return;
	}
	?>
	<input type="button" id="sg-quick-buynow" class="single_add_to_cart_button button alt" value="Buy Now" />
	<input type="hidden" name="sg_quick_buynow" value="" />
	<?php
	
}
add_filter( 'woocommerce_add_to_cart_redirect', 'salesgen_add_to_cart_redirect', 99, 2 );


function salesgen_add_to_cart_redirect( $url, $adding_to_cart )	{
	if ( 
		! isset( $_REQUEST['sg_quick_buynow'] ) || 
		! is_numeric( wp_unslash( $_REQUEST['sg_quick_buynow'] ) )
	) {
		return $url;
	}
	return wc_get_checkout_url();
}

add_action( 'wp_enqueue_scripts', 'salesgen_buynow_button_js' );

function salesgen_buynow_button_js() {
	$js_code = '
	(function($) {

		let buynow = $("#sg-quick-buynow");

		if ( buynow.get(0) ) {
			buynow.on("click", function (e){
				e.preventDefault();
				$("[name=sg_quick_buynow]").val("1");
				buynow.closest("form").submit();
			});
		}
	})(jQuery);
';
	wp_add_inline_script( 'woocommerce', $js_code );
	$salesgen_css = '
	#sg-quick-buynow{
	margin-top:15px;
	}
	';
	wp_add_inline_style( 'woocommerce-inline', $salesgen_css );
}

Leave a Reply

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