Display current category first then child categories in WooCommerce

Viewed 1070

I'm trying to display in the sidebar the current page's category and it's subcategories. The title should be the current category's name and linked to the current category as well. An example of what I'm trying to achieve can be seen here in the sidebar: https://food52.com/shop/pantry

This is my current site as an example:https://farmtofrank.wpengine.com/product-category/prepared-foods/

This is the code I've created so far:

<?php

$terms = get_terms([
    'taxonomy' => get_queried_object()->taxonomy,
    'parent'   => get_queried_object_id(),
]);

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );

echo '<div>';
foreach ( $terms as $term) {
    echo '<p class="filters"><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></p>';  
}
echo '</div>';

?>

It works but it puts the parent link at the bottom of the list. How can I keep the parent link at the top above the subcategories?

1 Answers

I suppose that this is related to product category archive pages. In this case, you are very near, try:

$queried_object = get_queried_object();

if ( is_product_category() && is_a($queried_object, 'WP_Term') ) {
    $taxonomy  = $queried_object->taxonomy;

    echo '<h2 class="shop__sidebar-heading">
    <a href="' . get_term_link( $queried_object ) . '">' . $queried_object->name . '</a>
    </h2>';

    $children_terms = get_terms(['taxonomy' => $taxonomy, 'parent' => $queried_object->term_id]);

    if ( ! empty($children_terms) ) {
        echo '<ul class="'.$queried_object->slug.' child-terms">';

        // Loop through children terms
        foreach ( $children_terms as $term) {
            echo '<li class="filters"><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
        }

        echo '</ul>';
    }
}

Tested and works. It will require some styling (CSS).

Related