How to add a shortcode function that returns the taxonomy slug of the actual post within the loop

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;
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x