psycho developer
psycho developer

Reputation: 242

Access downloadable data from WooCommerce downloadable products

I'm trying to fetch the WooCommerce products meta data using $product = new WC_Product( get_the_ID() ); I'm getting the product price and all the other values the products are downloadable WooCommerce products, I want to fetch the following data:

enter image description here

Whenever i try to fetch $product->downloads->id or $product->downloads->file i'm getting null in return. Please tell me what i'm doing wrong over here.

Upvotes: 3

Views: 4356

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253784

To access all product downloads from a downloadable product you will use WC_Product get_downloads() method.

It will give you an array of WC_Product_Download Objects which protected properties are accessible through WC_Product_Download available methods (since WooCommerce 3):

// Optional - Get the WC_Product object from the product ID
$product = wc_get_product( $product_id );

$output = []; // Initializing

if ( $product->is_downloadable() ) {
    // Loop through WC_Product_Download objects
    foreach( $product->get_downloads() as $key_download_id => $download ) {

        ## Using WC_Product_Download methods (since WooCommerce 3)

        $download_name = $download->get_name(); // File label name
        $download_link = $download->get_file(); // File Url
        $download_id   = $download->get_id(); // File Id (same as $key_download_id)
        $download_type = $download->get_file_type(); // File type
        $download_ext  = $download->get_file_extension(); // File extension

        ## Using array properties (backward compatibility with previous WooCommerce versions)

        // $download_name = $download['name']; // File label name
        // $download_link = $download['file']; // File Url
        // $download_id   = $download['id']; // File Id (same as $key_download_id)

        $output[$download_id] = '<a href="'.$download_link.'">'.$download_name.'</a>';
    }
    // Output example
    echo implode('<br>', $output);
}

Related answers:

Upvotes: 3

Shoelaced
Shoelaced

Reputation: 881

If you're trying to get the download link, try:

$downloads = $product->get_downloads();

This should return an array, so you can use it for example like:

foreach( $downloads as $key => $download ) {
    echo '<a href="' . $download["file"] . '">Download File</a>';
}

Upvotes: 1

Related Questions