4

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?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Felicia Santos
  • 401
  • 3
  • 16

1 Answers1

4

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).

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Quick question. The subcategories contain no children, so I wanted to display the parent category and parent category children in the childrens archive pages. How would I go about doing this? An example of what I'm trying to achieve is here: https://food52.com/shop/pantry/candy-chocolate PANTRY is the parent page, but even if you are in CANDY & CHOCOLATE it still shows the parent category in the sidebar with the same parent category children. – Felicia Santos Sep 23 '20 at 21:28
  • May be you could ask a new question about this, and notify me here, as I can't handle this here. – LoicTheAztec Sep 23 '20 at 22:42