我在wordpress循环中有以下代码,它应该找到自定义分类法的段塞:
$bands_array = get_the_terms($post->ID, 'tcu_song_bands');
$bands = '';
foreach( (array)$bands_array as $band ) {
$bands .= "band-" . $band->slug . " ";
}
然而,在我的debug.log中,我得到错误"试图获得非对象的属性"(然而,代码正在工作-但我正试图解决错误)。谁能建议一种不同的方法来获取自定义分类法的属性?
以下是我使用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
可能导致错误状态。该函数返回的可能性很重要。
(array|false|WP_Error)成功时WP_Term对象的数组,如果没有条件或职位不存在则为false,失败时WP_Error。
当你失去了它的可见性时,请不要使用它。
$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.