How to output permalink for term on WordPress posts in loop?

I have a series of posts within a custom post type which are all have a term within the taxonomy “collection.” Each post is associated with no more than one term within the “collection” taxonomy. I want to create a link under each post that says something like “More in this Collection,” how can I dynamically create a link to the term that it belongs in?

When I use the following snippet, it shows a list of terms as links. I just need the permalink so I can create that custom link, and not the name of the term associated with it.

Read More
<?php echo get_the_term_list( $post->ID, 'collection', '', ', ', '' ); ?>

What I’m trying to accomplish is a dynamic way to write something like this:

<a href="TERM_PERMALINK">More in this Collection</a>

Related posts

Leave a Reply

4 comments

  1. Here’s an example using get_term_link() and actually outputting the link as you described.

    $collections = get_the_terms($post->ID, 'collection');
    
    foreach ($collections as $collection){
        echo "<a href='".get_term_link($collection->slug, 'collection')."'>".$collection->name."</a>";
    }
    
  2. You’re going to want to use get_the_term to get an array of the terms used for the post. You can then loop through that array to create the permalinks.

    get_the_terms( $post->ID, 'collection' )
    

    This will return an array that fits the following structure:

    Array
    (
        [0] => stdClass Object
            (
                [term_id] => ...
                [name] => ...
                [slug] => ...
                [term_group] => ...
                [term_taxonomy_id] => ...
                [taxonomy] => collection
                [description] => ...
                [parent] => ...
                [count] => ...
            )
    )
    

    A simple loop through this array will allow you to parse your permalinks in whatever format you want, though I recommend http://site.url/TAXONOMY/TERM personally.

    $collections = get_the_terms( $post->ID, 'collection' );
    
    foreach( $collections as $collection ) {
        $link = get_bloginfo( 'url' ) . '/collection/' . $collection->slug . '/';
        echo $link;
    }
    

    In my code snippet I’m echoing out the permalink. You can do whatever you want with it (store it in an array, use it in a link definition, or really anything.