To limit the results to the children of the current product category, you can use parent
parameter in get_terms(). The id
of the current category, to be set as the parent
value, will be get using get_queried_object().
$term_id = 0;
$queried_object = get_queried_object();
//
// check if it's a custom category
if ( $queried_object instanceof WP_Term )
$term_id = $queried_object->term_id;
$args = array(
'taxonomy' => 'product_cat',
'parent' => $term_id, // get only direct children
//'child_of' => $term_id, // get all children
//'hide_empty' => false,
);
$terms = get_terms( $args );
If you would like to attach the current category to the results (before the child categories):
$terms = get_terms( $args );
if ($queried_object instanceof WP_Term) {
array_unshift( $terms, $queried_object );
}
An example of the code in its entirety:
if ( is_archive('product') ) // OR: is_product_category()
{
$term_id = 0;
$queried_object = get_queried_object();
//
// check if it's a custom category
if ( $queried_object instanceof WP_Term )
$term_id = $queried_object->term_id;
$args = array(
'taxonomy' => 'product_cat',
'parent' => $term_id, // get only direct children
//'child_of' => $term_id, // get all children
//'hide_empty' => false,
);
$terms = get_terms( $args );
//
// add current category at beginning
if ($queried_object instanceof WP_Term) {
array_unshift( $terms, $queried_object );
}
//
// Check if any term exists and print them all
if ( ! empty( $terms ) && is_array( $terms ) )
{
echo '<ul>';
foreach ( $terms as $term ) {
printf('<li><a href="https://wordpress.stackexchange.com/questions/336877/%s">%s</a></li>',
esc_url( get_term_link( $term ) ),
$term->name
);
}
echo '</ul>';
}
}