php - 在 woo 中获取对象的 get_the_terms 时出现 PHP 错误
问题描述
您好,我刚刚在我的 wordpress / woocommerce 网站的 debug.log 中收到了这些消息:
[21-Jul-2020 17:33:33 UTC] PHP Notice: Trying to get property 'name' of non-object in /home/lattyteskl/www/latty-com/wp-content/themes/betheme-child/functions.php on line 87 [21-Jul-2020 17:33:35 UTC] PHP Notice: Trying to get property 'term_id' of non-object in /home/lattyteskl/www/latty-com/wp-content/themes/betheme-child/functions.php on line 87
这是我使用的代码:
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ) {
if ( $term->term_id == $OUTILLAGE_ID )
{
$cats[] = '<a href="/catalogue-produits/outillage/">' . $term->name . '</a>';
}
您知道如何以更好的方式获得这些条款吗?
谢谢你
编辑:我在 debug.log 中添加了这一行:
[23-Jul-2020 08:20:46 UTC] PHP Notice: post was called <strong>incorrectly</strong>. Product properties should not be accessed directly. Backtrace: require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/betheme-child/woocommerce/single-product.php')
解决方案
您没有检查何时$terms
为空。我也认为你想打电话$product
而不是在$post
这里。get_id()
这将为您提供通过 WooCommerce功能获取 id 的选项。所以你的代码应该是这样的:
global $product;
$terms = get_the_terms( $product->get_id(), 'product_cat' );
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
if ( $term->term_id == $OUTILLAGE_ID ) {
$cats[] = '<a href="/catalogue-produits/outillage/">' . $term->name . '</a>';
}
}
}
推荐阅读
- java - 如何从文件中读取并将其存储在对象的 ArrayList 中?
- python - ascii'编解码器在打开 unicodeReader 时无法解码字节 0xe2 和 0x92
- haproxy - 用于 Haproxy 的 Opentracing 模块
- python - 如何在 keras 中使用 Conv2D.set_weights?
- c - 如何在c中打印一个无符号的int *?
- apache-kafka - 重置为 Kafka 分区中的自定义偏移量
- encryption - 如何以编程方式解密莲花笔记的加密电子邮件?
- javascript - 如何将配置文件添加到exe中。内置电子js
- newman - 如何将文件夹下的所有 CSV 数据文件提供给 newman 脚本并执行?
- java - Apache Nifi 与 kafka SASL_PLAINTEXT 的连接问题