首页 > 解决方案 > 从 WooCommerce 可下载产品访问可下载数据

问题描述

我正在尝试获取 WooCommerce 产品元数据,使用$product = new WC_Product( get_the_ID() );我正在获取产品价格以及产品是可下载的 WooCommerce 产品的所有其他值,我想获取以下数据:

在此处输入图像描述

每当我尝试获取$product->downloads->id$product->downloads->file我得到 null 作为回报。请告诉我我在这里做错了什么。

标签: phpwordpresswoocommercedownloadproduct

解决方案


要从可下载产品访问所有产品下载,您将使用WC_Product get_downloads()方法

它将为您提供一组WC_Product_Download对象,这些对象可通过WC_Product_Download可用方法访问受保护的属性 (自 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);
}

相关答案:


推荐阅读