admin管理员组文章数量:1320785
I want to output all the terms in my custom taxonomy and at the same time add a class to any of these that are attached to the current post.
I'm doing this in a custom shortcode that displays on each single post page.
I've used get_terms() to show all the terms in the taxonomy but I can't work out how to check if each term is attached to the current post.
$terms = get_terms( array(
'taxonomy' => 'package',
'hide_empty' => false
) );
if (!empty($terms) && ! is_wp_error( $terms )) {
echo '<ul>';
foreach ($terms as $term) {
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
}
I want to output all the terms in my custom taxonomy and at the same time add a class to any of these that are attached to the current post.
I'm doing this in a custom shortcode that displays on each single post page.
I've used get_terms() to show all the terms in the taxonomy but I can't work out how to check if each term is attached to the current post.
$terms = get_terms( array(
'taxonomy' => 'package',
'hide_empty' => false
) );
if (!empty($terms) && ! is_wp_error( $terms )) {
echo '<ul>';
foreach ($terms as $term) {
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
}
Share
Improve this question
edited Oct 1, 2020 at 11:36
FreddieE
asked Sep 30, 2020 at 16:40
FreddieEFreddieE
1134 bronze badges
1
|
1 Answer
Reset to default 1how to check if each term is attached to the current post
You can do that using has_term()
which defaults to checking on the current post in the main loop, hence you can omit the third parameter (the post ID).
So for example in your case:
$class = has_term( $term->term_id, $term->taxonomy ) ? 'active' : ''; // like this
//$class = has_term( $term->term_id, 'package' ) ? 'active' : ''; // or this
echo '<li class="' . $class . '">' . $term->name . '</li>';
本文标签:
版权声明:本文标题:Output all terms in a custom taxonomy and add a "active" class only to the ones attached to the current post 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742089492a2420178.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
taxonomy-my_tax.php
? And what is the "current post"? Where does it come from? – Sally CJ Commented Sep 30, 2020 at 19:52