php - 从 WooCommerce 可下载产品访问可下载数据
问题描述
我正在尝试获取 WooCommerce 产品元数据,使用$product = new WC_Product( get_the_ID() );
我正在获取产品价格以及产品是可下载的 WooCommerce 产品的所有其他值,我想获取以下数据:
每当我尝试获取$product->downloads->id
或$product->downloads->file
我得到 null 作为回报。请告诉我我在这里做错了什么。
解决方案
要从可下载产品访问所有产品下载,您将使用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);
}
相关答案:
推荐阅读
- vue.js - 使用带有插槽的 Vue 组件包装 DOM-Element 创建外部库
- google-apps-script - 在谷歌脚本中的单个谷歌表格中收集谷歌表单结果
- omnet++ - 如何在 VEINS 中呈现 SUMO 中的那些红绿灯?
- python - 如何确定 `TypeError: unsupported operand type(s) for /: 'float' and 'list'`的原因
- android - 在约束视图中为 imageView 设置 minHeight 不起作用
- docker - 带有 Letsencrypt 的 Traefik V2.0 无法为域生成证书
- kotlin - 访问 Kotlin 字段而不运行它的 getter
- javascript - 如何同步 SVG SMIL 动画?
- python-3.x - 清除气流任务导致 TypeError 错误(蘑菇云):无法腌制 SSLContext 对象
- c# - 代码高效的多条目参数 SQL 插入:C#