0

I am using the script below to list the custom taxonomies, but I still need a link to the parent of the current custom taxonomy for an "All" link.

Right now the links display as:

Shoes Shirt T-Shirt

Would like to include an "All" link so it will display as:

All Shoes Shirt T-Shirt

<?php       

$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
$children = get_term_children( $term->term_id, $term->taxonomy );
echo get_category_link( get_queried_object_id() );
if ( ! is_wp_error( $children ) && ! empty( $children ) ) {
wp_list_categories( 'taxonomy=' . $term->taxonomy . '&depth=1&show_count=0&title_li='. $title.'&child_of=' . $term->term_id );
} else {
wp_list_categories( 'taxonomy=' . $term->taxonomy . '&depth=1&show_count=0&title_li=&child_of=' . $term->parent );
} ?>
2

Try this, which worked well for me:

$term = get_queried_object();
$children = get_term_children( $term->term_id, $term->taxonomy );
$has_children = ( ! is_wp_error( $children ) && ! empty( $children ) );

// Has children, or no parent.
if ( $has_children || ! $term->parent ) {
    $parent =& $term; // reference to $term
// No children, but has parent.
} elseif ( $term->parent ) {
    // Get the term object (or data like name) using get_term().
    $parent = get_term( $term->parent );
}

echo '<h3><a href="' . esc_url( get_term_link( $parent ) ) . '">' . esc_html( $parent->name ) . '</a></h3>';
wp_list_categories( 'taxonomy=' . $term->taxonomy . '&depth=1&show_count=0&title_li=&child_of=' . $parent->term_id );

Explanation/Notes:

  • On a taxonomy archive, you should use get_queried_object() to get the.. queried term — just like when you visit a single post page, get_queried_object() would give you the queried post.

  • You can use get_term_link() to get the term archive URL (e.g. http://example.com/category/uncategorized).

  • I intentionally didn't use the title_li parameter because you're only displaying level 1 children (i.e. you set the depth parameter to 1).

And I used the h3 tag, but you can of course change it to your liking. :)

  • Worked perfect, I just removed the "esc_html( $parent->name )" and replaced that with all, and formatted it properly to blend right in. Thanks for the explanation! – Joe Landry Apr 5 '19 at 14:37
  • 2 for 2 Sally, you're on fire! – Joe Landry Apr 5 '19 at 17:47
  • I look forward to make it 3! ;) – Sally CJ Apr 6 '19 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.