首页 > 解决方案 > 在 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')

标签: phpwordpresswoocommerce

解决方案


您没有检查何时$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>';
        }
    }
}

推荐阅读