2

When I'm on a single post for a custom post type, I want to be able to grab the slug and name of the taxonomy term so I can insert them into a link. Below is what I've tried but it doesn't seem to work.

<?php

$term_slug = get_queried_object()->slug;
$term_name = get_queried_object()->name;

echo '<span class="back-button"><a href="/portfolio/' .$term_slug. '">&larr; Back to ' .$term_name. '</a></span>';

?>

So for example, if I'm on a single post for the custom post type "Projects" and the taxonomy term is "Album Artwork," I want to be able to grab the slug "album-artwork" and the name "Album Artwork" so I can put them into the link. How can I do this?

4

If you’re on a single post, then your code won’t work, because get_queried_object will contain the post (and not a term).

If you want to get terms of given post, you should use get_the_terms function.

$terms = get_the_terms( get_the_ID(), '<TAXONOMY_NAME>' ); // <- put real tax name in here

You also have to remember, that a post may have multiple terms assigned to it, so the line above will get you an array of terms. You can loop through it like so:

foreach ( $terms as $term ) {
     echo '<span class="back-button"><a href="/portfolio/' .$term->slug. '">&larr; Back to ' .$term->name. '</a></span>';
}

And the last thing...

You should never build term links like you do. There is a function for that to: get_term_link and you should use it instead of concatenating slug of a term with some strings (why? Because some plugins may change the structure of such links and your code will stop working then).

So the full code can look like this:

$terms = get_the_terms( get_the_ID(), '<TAXONOMY_NAME>' ); // <- put real tax name in here
if ( $terms and ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        echo '<span class="back-button"><a href="' . esc_attr( get_term_link( $term ) . '">&larr; Back to ' . esc_html($term->name) . '</a></span>';
    }
}
  • Thank you. How can I get the slug? The reason is because I don't want the link to go to the taxonomy link. I have my own link with "example.com/portfolio/slug" – Desi Apr 23 at 6:37
  • Exactly the same way as you get the name: $term->slug – Krzysiek Dróżdż Apr 23 at 6:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.