首页 > 解决方案 > WooCommerce - 在最后一个类别中获取(直接)父类别

问题描述

我想显示为链接,父类别(但不是祖父类别),只有当我查看最后/最深的类别时。为了更具表现力,当我浏览类别时,我有一些代码可以获取我所在的当前类别的子类别/子类别。代码是这样的

function sub_cats( $args = array() ) { 
    $terms = get_terms([
        'taxonomy' => get_queried_object()->taxonomy,
        'parent'   => get_queried_object_id(),
    ]);
    foreach ( $terms as $term) {
        echo '<li>';   
            echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';  
        echo '<li>';   
    }
}

由于我到达了每个类别树的最后一个/最深的类别/子项,因此我没有其他类别可以显示。现在我被要求显示为链接,只有最后/最深类别的直接父类别(不是祖父类别),然后才显示。

我想出的是,检查当前类别中是否有孩子,如果有,启动上面的代码。如果没有,则获取父类别。但在这里我把这一切都搞砸了,因为作为回报,我得到了数据库中所有属性和类别的结果。

//Get current category

$term = get_queried_object();
$children = get_terms( $term->taxonomy, array(
    'parent'    => $term->term_id,
    'hide_empty' => false
) );

//If this category has children then get me the children
if($children) {    
     $terms = get_terms([
        'taxonomy' => get_queried_object()->taxonomy,
        'parent'   => get_queried_object_id(),
    ]);
    foreach ( $terms as $term) {
        echo '<li>';   
        echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';  
        echo '<li>';   
    }
} else { //ELSE get me only the parent category -> HERE IS MY PROBLEM
    $caterms = get_terms( $product->ID, 'product_cat' );

    foreach ($caterms as $category) {
        if($category->parent == 0){
            echo '<li>';   
            echo '<a href="' . get_term_link( $category ) . '">' . $category->name . '</a>';  
            echo '<li>';  

        }
    } 
}

请帮忙

标签: woocommerceparent-child

解决方案


此函数获取 li 标签,所有产品类别,从第一/顶级类别到最后/最底层类别。然后,当您浏览到底部/最深的类别时,您将获得所有相同(最后/最深)级别的类别。因此,当您到达那些深层/最后的类别时,类别树并不会消失。

function sub_cats( $args = array() ) { 
    $term       = get_queried_object(); //get current term
    $children   = get_terms( $term->taxonomy, array( //get term children
                'parent'        => $term->term_id,
                'hide_empty'    => false
                ) );

    if($children) {    
        $terms = get_terms(
            array(
                'taxonomy' => $term->taxonomy,
                'parent'   => $term->term_id,
            )
        );
        foreach ( $terms as $term) {
            echo '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
                                    }
    } else {
        $term_children = get_terms(
                        'product_cat',
                                array(
                                    'parent' => $term->parent,
                                    )
                                    );
    if ( ! is_wp_error( $terms ) ) {
        foreach ( $term_children as $child ) {
        echo '<li><a href="' . get_term_link( $child ) . '">' . $child->name . '</a> 
    </li>';
                                            }
                                    }
        }
}

add_shortcode ('sub_cats', ' sub_cats' );

特别感谢 Panos(VG) 和 @Frits


推荐阅读