首先显示当前类别,然后显示 WooCommerce 中的 child 个类别

Display current category first then child categories in WooCommerce

我试图在边栏中显示当前页面的类别及其子类别。标题应该是当前类别的名称,并且 linked 到当前类别。在侧边栏中可以看到我正在努力实现的示例:https://food52.com/shop/pantry

以我当前的网站为例:https://farmtofrank.wpengine.com/product-category/prepared-foods/

这是我到目前为止创建的代码:

<?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>';

?>

有效,但它会将 parent link 放在列表的底部。如何让 parent link 保持在子类别上方的顶部?

我想这与产品类别存档页面有关。在这种情况下,你很近,试试:

$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>';
    }
}

已测试并有效。它需要一些样式 (CSS)。