Display the download link for products already purchased by the customer in Woocommerce products loop

I'm running basic product loop with featured image and title. Under that I want download link to be available if the user has bought that digital product.

I tried this but it shows downloadable bought product links under all products in the loop.

I want the downloadable links (that the customer has bought) to be under the bought products only.

global $product;

$downloads = array();

$user_id = get_current_user_id();

$downloads = wc_get_customer_available_downloads($user_id);

if (!empty($downloads)) {

    foreach ($downloads as $download) {

        if ($download['product_id'] === $product->get_id()) {

            echo '<a href="' . $download['download_url'] . '">Download</a>';

        }
    }
}

1 answer

  • answered 2020-06-01 18:55 7uc1f3r

    This seems to do the trick (comment with explanation added to the code)

    function action_woocommerce_after_shop_loop_item_title(){
        global $product;
    
        if( ! is_a( $product, 'WC_Product') ) {
            $product = wc_get_product(get_the_ID());
        }
    
        // Get user id
        $user_id = get_current_user_id();
    
        // Get customer available downloads
        $downloads = wc_get_customer_available_downloads( $user_id );
    
        // NOT empty
        if ( ! empty( $downloads ) ) {
            // Loop
            foreach ( $downloads as $download ) {
                // Compare  
                if ( $download['product_id'] === $product->get_id() ) {
                    echo '<a href="' . $download['download_url'] . '">Download</a>';
                }
            }
        }
    }
    add_action( 'woocommerce_after_shop_loop_item_title', 'action_woocommerce_after_shop_loop_item_title', 10, 0 );