How to add a Woocommerce buy now button for variable products without plugin?

1k views Asked by At

I wish to ADD a "buy now" button on product page for variable products. I tried many snippets code but those are working only for simple products.

function add_content_after_addtocart() {

$current_product_id = get_the_ID();

$product = wc_get_product( $current_product_id );

$checkout_url = wc_get_checkout_url();

if( $product->is_type( 'simple' ) ){ echo 'Buy Now'; } } add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );

above code is only working for simple products. In the same way I would like to create buy now button on variation product page. Please do help

Thank you.

1

There are 1 answers

0
Priyanshu Kast On
function sbw_wc_add_buy_now_button_single()
{
    global $product;
    printf( '<button id="sbw_wc-adding-button" type="submit" name="sbw-wc-buy-now" value="%d" class="single_add_to_cart_button buy_now_button button alt">%s</button>', $product->get_ID(), esc_html__( 'Buy Now', 'sbw-wc' ) );
}

add_action( 'woocommerce_after_add_to_cart_button', 'sbw_wc_add_buy_now_button_single' );

/*** Add buy now button to product archive page ***/

function sbw_wc_add_buy_now_button_archive()
{
    global $product;
    if ( ! $product->is_type( 'simple' ) ) {
      return false;
    }
printf( '<a id="sbw_wc-adding-button-archive" href="%s?buy-now=%s" data-quantity="1" class="button product_type_simple add_to_cart_button  buy_now_button" data-product_id="%s" rel="nofollow">%s</a>', wc_get_checkout_url(), $product->get_ID(), $product->get_ID(), esc_html__( 'Buy Now', 'sbw-wc' ) );
}

add_action( 'woocommerce_after_shop_loop_item', 'sbw_wc_add_buy_now_button_archive', 20 );