I am using the following code to display my custom taxonomy slugs. However it is only displaying the first category and not all the related categories. I know this is fairly simple and is to do with [0] but I can’t figure out how to change it.
$getslugid = wp_get_post_terms( $post->ID, 'opd_taggallery' );
$getslug = $getslugid [0]->slug;
echo $getslug;
3 Answers
This is more of a PHP question, but the solution is simple – you need to use a foreach
-loop on $getslug
, because you just echo the slug of the first taxonomy.
The function wp_get_post_terms()
does not return a single object, but an array of objects. You are right with the [0]
, this indicates that you are checking the first entry of said array.
Your function should look something like this:
$getslugid = wp_get_post_terms( $post->ID, 'opd_taggallery' );
foreach( $getslugid as $thisslug ) {
echo $thisslug->slug . ' '; // Added a space between the slugs with . ' '
}