我正在尝试使用 $product = new WC_Product( get_the_ID() );
获取 WooCommerce 产品元数据我正在获取产品价格和产品的所有其他值是可下载的 WooCommerce 产品,我想获取以下数据:
每当我尝试获取 $product->downloads->id
或 $product->downloads->file
我得到 null 作为返回。请告诉我我在这里做错了什么。
最佳答案
要访问可下载产品的所有产品下载,您将使用 WC_Product
get_downloads()
method .
它将为您提供一组WC_Product_Download
对象,这些对象的 protected 属性可通过WC_Product_Download
available methods 访问。 (自 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);
}
相关回答:
关于php - 从 WooCommerce 可下载产品访问可下载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62201288/