List the term slug or name of current post

The ‘get_the_terms()’ helps to retrieve term values form a custom taxonomy in WordPress. What results is an array. So we use foreach() loop to get individual data. Then we pass it into an array and then join it later. You can get any values related with the term using this foreach loop. Just make sure you enter the right object value.

//Remember to paste this code inside WORDPRESS LOOP
$terms = get_the_terms( $post->ID, 'custom_taxonomy');
if ( $terms && ! is_wp_error( $terms ) ) {
    //we create an array to store the values
    $term_slug = array();
    foreach ( $terms as $term ) {
        $term_slug[] = $term->slug;
        //if you want to list 'name' then replace '$term->slug' with '$term->name'
    //finally join the array.
    $term_slug = join( ", ", $term_slug );
    //Now just echo it out.
    echo term_slug;

Latest Comments

Leave a Reply

comment on this article