Hi there,
I'm struggling with taxonomies. Basically I've a custom post type using taxonomies looking like this:
Tax_Parent
- Tax_Child
- Tax_Child
-- Tax_Child2
-- Tax_Child2
- Tax_Child
Tax_Parent
- Tax_Child
-- Tax_Child2
-Tax_Child
So first of all, I'd like a list with only Tax_Parent (but I don't want to "exclude").
And then, I'd like to have a second list but only with Tax_Child and each child should have a <em>rel="Tax_Parent-slug"</em>.
Is it possible?
Thanks for your help.
Cheers,
Thomas
Michael Fields answers:
This is one way of doing it:
<?php
$terms = array();
$_terms = get_terms( 'category' );
foreach( (array) $_terms as $term ) {
$terms[$term->term_id] = $term;
}
/*
* List parents.
*/
print "\n\n\n" . '<ul>';
foreach ( $terms as $term ) {
if ( ! empty( $term->parent ) ) {
continue;
}
print "\n" . '<li><a href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . esc_html( $term->name ) . '</li>';
}
print "\n" . '</ul>';
/*
* List all but "root" terms.
*/
print "\n\n\n" . '<ul>';
foreach( $terms as $term ) {
if ( empty( $term->parent ) ) {
continue;
}
print "\n" . '<li><a rel="' . esc_attr( $terms[$term->parent]->slug ) . '" href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . esc_html( $term->name ) . '</li>';
}
print "\n" . '</ul>';
Thomas comments:
Hi Michael,
Thank you for your quick reply.
It's almost perfect but your <blockquote>List all but "root" terms</blockquote> displays the children of a child (aka Tax_Child2 in my example) and I only want the 1st level of children.
Cheers,
Thomas
Michael Fields comments:
No worries. Please try:
$terms = array();
$root_ids = array();
$_terms = get_terms( 'category' );
foreach( (array) $_terms as $term ) {
$terms[$term->term_id] = $term;
}
/*
* List root terms.
*/
print "\n\n\n" . '<ul>';
foreach ( $terms as $term ) {
if ( ! empty( $term->parent ) ) {
continue;
}
$root_ids[] = $term->term_id;
print "\n" . '<li><a href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . esc_html( $term->name ) . '</li>';
}
print "\n" . '</ul>';
/*
* List all direct descendants of root terms.
*/
print "\n\n\n" . '<ul>';
foreach( $terms as $term ) {
if ( empty( $term->parent ) ) {
continue;
}
if ( ! in_array( $term->parent, $root_ids ) ) {
continue;
}
print "\n" . '<li><a rel="' . esc_attr( $terms[$term->parent]->slug ) . '" href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . esc_html( $term->name ) . '</li>';
}
print "\n" . '</ul>';
Thomas comments:
Hi Michael,
Thank you so much for your help. It's working fine.
Cheers,
Thomas