Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jorpdesigns/3657eb7d51937a61a6618b7ee89b72df to your computer and use it in GitHub Desktop.
Save jorpdesigns/3657eb7d51937a61a6618b7ee89b72df to your computer and use it in GitHub Desktop.
Snippet to replace "Add to Cart" with "Download" button on WooCommerce product page if logged-in customer has purchased downloadable product
<?php
// IMPORTANT: Add customer_has_download() function from here - https://gist.github.com/jorpdesigns/d155eaf0fe3260b0f59d514cca5004ed
add_action( 'template_redirect', 'product_single_download_button_check' );
function product_single_download_button_check() {
if ( customer_has_download( get_queried_object_id() ) ) {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', 'product_single_download_button', 30 );
}
}
// Create product_download__single_button() function
function product_single_download_button() {
global $product;
$user_id = get_current_user_id();
$downloads = wc_get_customer_available_downloads( $user_id );
foreach ($downloads as $download) {
if ( $download['product_id'] === $product->get_id() ) {
echo '<a href="' . $download['download_url'] . '" class="button alt">Download</a>';
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment