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? *WITH LIST* WordPress

  • SOLVED

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!

Answers (1)

2011-03-03

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!