Show all wp_get_post_terms slugs

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;

Related posts

Leave a Reply

3 comments

  1. 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 . ' '
    
    }
    
  2. In newer WordPress versions it is possible to directly query only the taxonomy slugs. I think this came with the introduction of the WP_Term_Query class in WP version 4.6.0.

    $slugs = wp_get_post_terms( $post->ID, 'opd_taggallery', array( 
        'fields' => 'id=>slug',
    ) );
    echo implode( " ", $slugs );