Same level categories in Woocommerce?

Viewed 55

I didn't find any resource explaining how to do this which seems really odd, so I'm asking the questions here.

I want to display, on the category page, the same level categories. I already display the sub-categories with the widget, but I cannot find a way to display the categories from the same level.

Is there any way to do that?

Thanks

I have tried a plugin called "X product filters" which offers this functionality, but it doesn't work

1 Answers

If you are trying to list all the child categories of the same parent category, you can try something like this:

<?php
    // Get current category
    $current = get_queried_object();

    // Get parent ID
    $parents = get_ancestors( $current->term_id, 'product_cat' );
    $parent_id = get_term_by( 'id', $parents['0'], 'product_cat' ) ;
?>

<?php

// Loop through categories
$terms = get_terms( 'product_cat' );


echo '<ul>';
 
foreach ( $terms as $term ) {
 
    $term_link = get_term_link( $term );
    
    // Skip categories with different parent categories
    if($current->parent != $term->parent) {
        continue;
    }
 
    echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
}
 
echo '</ul>';

?>
Related