0

Circumstances: I have a CPT called "designs" and a taxonomy related to it, called "project_category" so that I can assign a category to each design. I'm building the template for each 'design' and I need a shortcode that returns the assigned project category SLUG of the current design within the loop.

It's important that I retrieve the slug instead of the ID because I'll be using the shortcode to wrap the whole template and assign it an #ID name so I can then target it with a link.

Example: I have a design post called "New logo for Pepsi" which has "Visual Identity" as it's project category. So I'd need the shortcode to return "visual_identity" instead of "Visual Identity".

Facts to consider: each design will have only one category assigned, so I don't need the shortcode to return an array, only a single slug.

I guess it should be something like this:

add_shortcode( 'return_taxonomy_slug', 'my_shortcode_return_taxonomy_slug' );

function my_shortcode_return_taxonomy_slug() {
    return get_the_terms( $designs, $project_category->slug );
}

...or maybe something like this to work-around:

add_shortcode( 'return_taxonomy_slug', 'my_shortcode_return_taxonomy_slug' );

$terms = wp_get_post_terms( get_the_ID(), 'project_category');

function my_shortcode_return_taxonomy_slug() {
    return $terms->slug;
}

1 Answer 1

0

get_the_terms() will always return an array; but because you have only one 'project_category', you can simply use its first element:

add_shortcode( 'return_taxonomy_slug', 'my_shortcode_return_taxonomy_slug' );
function my_shortcode_return_taxonomy_slug() {
  $terms = get_the_terms( get_the_ID(), 'project_category');
  return $terms[0]->slug;
}
1
  • Works like a charm! Thank you so much, kind sir! I really appretiate it
    – Ernest
    May 2, 2021 at 9:50

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.