php - WooCommerce custom sidebar for category page (Identify parent cat)

one text

I've put together a custom filter sidebar for my WooCommerce Category page.

Some info about the sidebar:

  • It pulls in all active product categories, allowing flexibility for the client to add more down the road.
  • Each item clicks through to its appropriate category page.
  • One parent category is hidden from the loop (id 122).
  • The initial loop calls in parent categories
  • The sub loop pulls in child categories (If there are any & if they have products).
  • I'm using $product_cat to identify if the current category page is the same as the cat in the sidebar, allowing a class to be added so it can be highlighted when on the page.

Q Much like with what I've done with $product_cat, I would like to be able to identify within the loop IF the parent category on the sidebar is the parent of the child category page the user is currently on. With this in place, I can then add a class to the parent category li.

I've spent some time crawling the website in an attempt to find a solution but sadly not.

My full code below:

global $wp_query;

    $cat_name = "product_cat";
    $parent_cat_terms = get_terms($cat_name, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => true, 'exclude' => 122 ));

    // IF Current declaration
    global $wp_query;
    $product_cat = $wp_query->query_vars['product_cat'];

    echo '<ul class="cat-filters">';
        foreach ($parent_cat_terms as $parent_term) {

            if( $parent_term->count > 0 ):

                echo '<li class="cat-parent';
                    if( $parent_term->slug == $product_cat ){
                        echo ' class="page-cat"';
                    }
                echo '"><a href="' . get_term_link($parent_term) . '"';
                    if (strpos($parent_term->slug, $product_cat ) !== false) {
                        echo ' class="page-cat"';
                    }
                    echo'>' . $parent_term->name . '</a>';

                    $child_cat_terms = get_terms($cat_name, array('parent' => $parent_term->term_id, 'orderby' => 'slug', 'hide_empty' => true));

                    if ( !empty( $child_cat_terms ) && !is_wp_error( $child_cat_terms ) ){
                        echo '<ul class="cat-child">';

                        foreach ($child_cat_terms as $child_term) {

                            if( $child_term->count > 0 ):

                                echo '<li><a href="' . get_term_link($child_term) . '"';
                                if( $child_term->slug == $product_cat ){
                                    echo ' class="page-cat"';
                                }
                                echo'>' . $child_term->name . '</a></li>';

                            endif;

                        }

                        echo "</ul>";

                    }

                 echo '</li>'; 

            endif;

        }
    echo '</ul>';

Source