On a taxonomy archive page, be it for a child or parent term, you can get the current/queried term object/data using get_queried_object()
which contains properties like term_id
(the term ID) and slug
(the term slug). And the property name for the ID of the parent term is parent
. So you can do so to get the parent’s term ID:
$cat = get_queried_object();
$parent_cat_id = $cat->parent;
And for displaying a list of terms in the parent term, you can use wp_list_categories()
. Here’s an example with the title_li
set to ''
and echo
set to 0
, which means I’m manually putting the output into an UL
(<ul></ul>
):
$cat = get_queried_object();
$list = wp_list_categories( [
'taxonomy' => $cat->taxonomy,
'child_of' => $cat->parent,
'title_li' => '',
'echo' => 0,
] );
if ( $list ) {
echo "<ul>$list</ul>";
}
If you want full control over the HTML, e.g. to add custom HTML before/after the term link or perhaps to add custom CSS classes, you can use get_terms()
and loop through the term objects to display the term:
$cat = get_queried_object();
$cats = get_terms( [
'taxonomy' => $cat->taxonomy,
'child_of' => $cat->parent,
] );
if ( ! empty( $cats ) ) {
echo '<ul>';
foreach ( $cats as $cat ) {
$url = esc_url( get_category_link( $cat ) );
// change the 'before' and/or 'after' or whatever necessary
echo "<li>before <a href="https://wordpress.stackexchange.com/questions/360088/$url">$cat->name</a> after</li>";
}
echo '</ul>';
}