【问题标题】:Display current category first then child categories in WooCommerce在 WooCommerce 中先显示当前类别,然后显示子类别
【发布时间】:2021-01-09 01:15:12
【问题描述】:

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

?>

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

【问题讨论】:

    标签: php html wordpress woocommerce taxonomy-terms


    【解决方案1】:

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

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

    【讨论】:

    • 快速提问。子类别不包含子类别,因此我想在儿童档案页面中显示父类别和父类别子项。我该怎么做呢?我正在尝试实现的一个示例如下:food52.com/shop/pantry/candy-chocolate PANTRY 是父页面,但即使您在 CANDY & CHOCOLATE 中,它仍会在侧边栏中显示父类别以及相同的父类别子项。
    • 也许您可以就此提出一个新问题,并在此处通知我,因为我无法在此处处理此问题。
    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多