Access downloadable data from WooCommerce downloadable products

假装没事ソ 提交于 2020-06-28 03:38:39

问题


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:

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.


回答1:


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:

  • Add downloads in Woocommerce downloadable product programmatically
  • Add programmatically a downloadable file to Woocommerce products



回答2:


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>';
}


来源:https://stackoverflow.com/questions/62201288/access-downloadable-data-from-woocommerce-downloadable-products

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!