在WooCommerce中先显示当前类别,然后显示子类别

问题描述

我试图在侧栏中显示当前页面的类别及其子类别。标题应该是当前类别的名称,并且还应该链接到当前类别。在边栏中可以找到我要实现的目标的示例: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>';

?>

它可以工作,但是将父链接放在列表的底部。如何将父链接保持在子类别上方的顶部?

解决方法

我想这与产品类别归档页面有关。在这种情况下,您距离很近,请尝试:

$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)。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...