I have registered one custom taxonomy. I am using this code to show this taxonomy on single.php
.
But it shows parent and child terms as well.
function showorganisation()
{
$terms = get_the_terms($post->ID, 'organization');
foreach ($terms as $term) {
$term_link = get_term_link($term, 'organization');
if (is_wp_error($term_link))
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
}
How can I make it show parent terms only?
I have registered one custom taxonomy. I am using this code to show this taxonomy on single.php
.
But it shows parent and child terms as well.
function showorganisation()
{
$terms = get_the_terms($post->ID, 'organization');
foreach ($terms as $term) {
$term_link = get_term_link($term, 'organization');
if (is_wp_error($term_link))
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
}
How can I make it show parent terms only?
Share Improve this question edited Mar 4, 2022 at 19:34 Fabrizio Mele 6875 silver badges16 bronze badges asked Mar 2, 2022 at 4:04 Prabhat JaniPrabhat Jani 11 bronze badge1 Answer
Reset to default 0get_the_terms()
gives you an array of WP_Term objects. The object has parent
(int) property, which tells you, if the term is a child and has a parent term or not.
This means that in your loop you can skip child terms with a simple if
statement.
foreach ($terms as $term) {
// Is it a child term?
if ( $term->parent ) {
continue;
}
// code...
}