skip to Main Content

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.

2

Answers


  1. 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>';
    }
    
    Login or Signup to reply.
  2. 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:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search