I posted a question the other day and received a useful answer, although I later realized that it didn't completely fulfill my needs.
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. And, I would also like to list only the continent (parent) in a separate location.
The following code supplied that for me, although I need it to create a list for all other posts with that share the value in the way that the code <strong>get_the_term_list</strong> does.
<strong>For listing children without parent:</strong>
$terms = get_the_terms(get_the_ID(), 'location');
$countries = array();
foreach ($terms as $term) {
if ($term->parent) $countries[] = $term->name;
}
echo 'Country: ' . implode(', ', $countries);
<strong>For listing parent without children:</strong>
$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);
Thanks!
rilwis answers:
Hi Jeremy,
Here's my fixed code :)
Put this function into your functions.php file:
function rw_get_the_term_list($id = null, $taxonomy, $parent = true, $before = '', $sep = ', ', $after = '') {
$id = empty($id) ? get_the_ID() : $id;
$terms = get_the_terms($id, $taxonomy);
$html = array();
foreach ($terms as $term) {
if (($parent && 0 == $term->parent) || (!$parent && $term->parent)) {
$html[] = '<a href="' . get_term_link($term, $taxonomy) . '">' . $term->name . '</a>';
}
}
return $before . implode($sep, $html) . $after;
}
And in your theme files, call it (very similar to get_the_term_list, except 1 parameter "$parent" which is true or false):
<?php echo rw_get_the_term_list(null, 'location', false, 'Countries: ', ', ', ''); ?>
Jeremy Phillips comments:
Perfect! Thanks so much!