Free Download Button on Product Page Woocommerce

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', 'itl_woocommerce_template_single_add_to_cart', 30 );

/*
 * replace WooCommerce add-to-cart button with download link when product is downloadable & free
 */
 
function itl_woocommerce_template_single_add_to_cart() {
	global $product;
	if ( $product->is_downloadable('yes') ) {
		if ( $product->get_price() > 0 ) {
			do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' );
		} else {
			$files = $product->get_files();
            $files = array_keys($files);
			$download_url = home_url('?download_file='.$product->id.'&key='.$files[0].'&free=1' );
			$button = sprintf( '<a href="%s" rel="nofollow" target="_black" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
            esc_url( $download_url  ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            $product->is_purchasable() && $product->is_in_stock() ? '' : '',
            esc_attr( $product->product_type ),
            esc_html( 'Download' )
        );
			echo $button;
		}
	} else {
		do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' );
	}
}

Leave a Reply

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