获取自定义分类法时出错 "Trying to get property of non object"

Error when getting slug of custom taxonomy "Trying to get property of non object"

我在 wordpress 循环中有以下代码,它应该找到自定义分类法的 slug:

$bands_array = get_the_terms($post->ID, 'tcu_song_bands');
$bands = ''; 

foreach( (array)$bands_array as $band ) {
    $bands .=  "band-" . $band->slug . " ";
}

但是,在我的 debug.log 中,我收到错误 "Trying to get property of a non object"(但是,代码正在运行 - 但我正在尝试解决错误)。任何人都可以建议一种不同的方法来获取自定义分类法的 slug 吗?

这是我在使用 print_r($band)

时得到的单个结果
WP_Term Object ( [term_id] => 15 [name] => 5-piece [slug] => 5-piece [term_group] => 0 [term_taxonomy_id] => 15 [taxonomy] => tcu_song_bands [description] => [parent] => 0 [count] => 165 [filter] => raw )

get_the_terms 可能导致错误状态。该函数的 return 可能性很重要。

(array|false|WP_Error) Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.

不要费心投射它,因为你看不到它。

$bands_array = get_the_terms($post->ID, 'tcu_song_bands');
$bands = ''; 

if (is_array($bands_array)) {
    foreach($bands_array as $band) {
        // only interested in bands with a slug
        if (isset($band->slug)) {
            $bands .=  "band-" . $band->slug . " ";
        }
    }
} 
// else log error if it returned a WP_Error, etc.