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 thedepth
parameter to1
).
And I used the h3
tag, but you can of course change it to your liking. 🙂