I would like to use a shortcode in WordPress to output all the categories that a post is tagged to. With the PHP code I created, all categories are now displayed. How can I get it to display only those. Which are used in the post on what the shortcode is included? Thanks for your help!
function get_cat($post_id) {
$terms = get_terms( array(
'taxonomy' => 'test',
'hide_empty' => true,
) );
echo '<br><strong>Test: </strong>';
foreach ($terms as $term){
echo '<a target="_blank" href="/test/'. $term->slug . '/">' . $term->name . '</a>';
echo ' ';
}
}
add_shortcode( 'get_cat', 'get_cat' );
CodePudding user response:
If you want to get the categories of the current post in which the shortcode was used then you can change the function where you get your categories which in your case is the get_terms with get_the_terms() function.
Solution:
Change this:
$terms = get_terms( array(
'taxonomy' => 'test',
'hide_empty' => true,
) );
To this:
$terms = get_the_terms(get_the_ID(), 'category');
The second parameter is taxonomy, change to your desired taxonomy I tested it with the default one which is 'category', in your case it is 'test' based on your code.
With this change, you'll be able to see only categories that are used on that particular post.
Other solution:
If you want to use the default taxonomy (category), you can use this function get_the_category()
With this solution you'd have to pass only the post id as a parameter like this:
$terms = get_the_category(get_the_ID());
Note: This function only returns results from the default "category" taxonomy. For custom taxonomies use the first solution with get_the_terms() function.