nurain nurain - 1 year ago 47
PHP Question

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.

<?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>

Answer Source

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:

    [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.