Search code examples
phpwordpresswoocommercedownloadorders

Add Product File Download Link to Thank You Page WooCommerce


I am using this code so that the customer can download the file directly from the Thank You page after the purchase has been completed. Problem is, it's giving me an error saying "WP_Hook->apply_filters(NULL, Array) "

Here's the code I'm using:

add_action( 'woocommerce_thankyou', 'add_download_link_to_thank_you_page' );
function add_download_link_to_thank_you_page() {
$downloads = $product->get_files();
foreach( $downloads as $key => $each_download ) {
  echo '<a href="'.$each_download["file"].'">Download Item</a>';
}}

Don't understand what's wrong with it.


Solution

  • The variable $product is not defined in your code and the hook argument $order_id is missing from the function.

    Also you need to use WC_Order get_downloadable_items() method that is more efficient with orders.

    Normally the downloadable items are displayed in a specific table before the order details (when there is downloadable items, depending on permissions settings), so it's very strange that you are trying to display them otherwise.

    So try the following instead:

    add_action( 'woocommerce_thankyou', 'add_download_links_to_thank_you_page' );
    function add_download_links_to_thank_you_page( $order_id ) {
        $order = wc_get_order( $order_id );
        $html  = [];
    
        if( $downloads = $order->get_downloadable_items() ) {
            foreach( $downloads as $download ) {
                $html[] = '<a href="'.$download["file"]['file'].'">' . __('Download') . ' "' . $download["file"]['name'] . '"</a>';
            }
        }
    
        if( ! empty($html) ){
            echo implode('<br>', $html);
        }
    }
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.


    To display that downloads before order details table, you will replace:

    add_action( 'woocommerce_thankyou', 'add_download_links_to_thank_you_page' );
    

    by

    add_action( 'woocommerce_thankyou', 'add_download_links_to_thank_you_page', 10, 5 );