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="https://wordpress.stackexchange.com/portfolio/" .$term_slug. '">← 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?
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="https://wordpress.stackexchange.com/portfolio/" .$term->slug. '">← 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 ) . '">← Back to ' . esc_html($term->name) . '</a></span>';
}
}