Skip to content

Instantly share code, notes, and snippets.

@jchamb
Last active July 25, 2023 16:59
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jchamb/fdf7d12b0191cb852056 to your computer and use it in GitHub Desktop.
Save jchamb/fdf7d12b0191cb852056 to your computer and use it in GitHub Desktop.
Woocommerce Free Downloads without checkout
function direct_free_downloads_button($button)
{
global $product;
if( $product->is_downloadable() AND $product->get_price() == 0 )
{
$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" 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' )
);
}
return $button;
}
add_filter('woocommerce_loop_add_to_cart_link', 'direct_free_downloads_button', 100);
/**
* Handles downloading of free Downloadable products
* @return [type] [description]
*/
function download_free_product_file()
{
$product_id = absint( $_GET['download_file'] );
$_product = wc_get_product( $product_id );
if( $_product->get_price() == 0 ) {
WC_Download_Handler::download( $_product->get_file_download_path( filter_var($_GET['key'], FILTER_SANITIZE_STRING) ), $product_id );
}
}
if ( isset( $_GET['download_file'] ) && isset( $_GET['key'] ) && $_GET['free'] ) {
add_action( 'init', 'download_free_product_file' );
}
@larodiel
Copy link

Nice, I've been searching for this long time, and it worked! 👍

@Alejorro
Copy link

Alejorro commented Mar 7, 2019

sorry to bother you, but where do i paste this?

@ozonostudio
Copy link

how use it?

@dsimi
Copy link

dsimi commented Feb 21, 2020

Add the code in your theme's functions.php

@akteotia
Copy link

Can i add Download Counter to it
Please help me

@braddus87
Copy link

braddus87 commented Jul 25, 2023

Hi - I'm using Woocommerce Product Tables to display MP3s. These are priced at 99p for individual downloads or a customer can purchase a subscription that gives a 100% discount on all downloads - so making them free. I want these subscribers to be able to click download and they instantly download - rather than them having to be taken to the checkout for each download. Can you help?

Cheers, Brad

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment