I have the following code inside a wordpress loop which should find the slug for a custom taxonomy:
$bands_array = get_the_terms($post->ID, 'tcu_song_bands');
$bands = '';
foreach( (array)$bands_array as $band ) {
$bands .= "band-" . $band->slug . " ";
}
However, in my debug.log I am getting the error "Trying to get property of a non object" (however, the code is working - but I'm trying to address the error). Can anyone suggest a different method for getting the slug of a custom taxonomy?
Here is what I get for a single result when using 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
can result in an error state. The return possibilities from that function are important.
(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.
Don't bother casting it as you lose visibility on that.
$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.