Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Exclude taxonomy parent when outputting in the loop? WordPress

  • SOLVED

I have places in my template where I need to display the name of a country. Right now, I have a taxonomy of "Location" that lists continent names as the parent and country names as the children. I would like to be able to list only countries (without continent names) within the loop.

This is the code I've started with:

<?php echo get_the_term_list( $post->ID, 'Location', 'Country: ', ', ', '' ); ?>
Example of what above code gives me: <strong>Country: Africa, Nigeria</strong>
where I would like: <strong>Country: Nigeria</strong>

The other thing is that I would also like to be able to output the parent category name without the children in specific locations as well.

Answers (3)

2011-03-01

rilwis answers:

You can try this code:

$terms = get_the_terms(get_the_ID(), 'location');
$countries = array();
foreach ($terms as $term) {
if ($term->parent) $countries[] = $term->name;
}
echo 'Country: ' . implode(', ', $countries);


Jeremy Phillips comments:

Thank you, that worked very well! Just one more thing, how could I show just the continent (parent) name without the children (countries)?


rilwis comments:

Just change a bit in the code:

$terms = get_the_terms(get_the_ID(), 'location');
$continent = array();
foreach ($terms as $term) {
if (0 == $term->parent) $continent[] = $term->name;
}
echo 'Continient: ' . implode(', ', $continent);

2011-03-01

Vidyut Kale answers:

<codel>

<?php wp_list_categories('child_of=1&title_li=&taxonomy=location' ); ?>

</code>

Where child_of=1 can be replaced by whichever continent's id you need.

To output only the parent category names without children, try

<?php wp_list_categories('depth=1&title_li=&taxonomy=location' ); ?>

2011-03-01

Nathan Epp answers:

to @rilwis 's code you can just add a ! infront of $term->parent

if ( !$term->parent ) $countries[] = $term->name;