Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jorpdesigns/7d4406520a70e3fd1a05226d6de97e45 to your computer and use it in GitHub Desktop.
Save jorpdesigns/7d4406520a70e3fd1a05226d6de97e45 to your computer and use it in GitHub Desktop.
Snippet to replace "Add to Cart" with "Download" button on WooCommerce archive 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( 'woocommerce_after_shop_loop_item', 'product_archive_download_button_check', 1 );
function product_archive_download_button_check() {
global $product;
if ( $product->is_downloadable() && customer_has_download( $product->get_id() ) ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
add_action( 'woocommerce_after_shop_loop_item', 'product_archive_download_button');
} else {
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
}
}
// Create product_archive_download_button() function
function product_archive_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