如何显示产品类别和子类别列表

时间:2021-04-20 11:10:43

标签: php wordpress woocommerce

我配置了以下产品类别结构:

  1. 类别 1
    • 子类别 1
    • 子类别 2
    • 子类别 3
  2. 第 2 类
    • 子类别 4
    • 子类别 5
    • 子类别 6

我想显示基于此行为的类别/子类别列表:

  • 在类别 1 中时:显示所有子类别 (1 + 2 + 3)
  • 在子类别 1 上时:显示类别 1 + 子类别 2 和 3
  • 在子类别 2 上时:显示类别 1 + 子类别 1 和 3
  • 在类别 2 中时:显示所有子类别 (4 + 5 + 6)
  • 在子类别 4 上时:显示类别 2 + 子类别 5 和 6

我已经尝试了很多不同的代码并得到了一些结果,但没有一个不排除当前子类别。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

感谢这两个帖子:this onethis one 我设法得到了结果!我还添加了一个代码来显示子类别时的父类别。

    $current_category = get_queried_object();

    /** PARENTS **/
    /** Get Category ID of current page **/
    $current_category_id = $current_category->term_id;

    /** Get Array of Category Parents **/
    $parent_cat = get_ancestors($current_category_id, 'product_cat');
       
    /** Get infos of first Parent **/
    $parent_cat_term = get_term( $parent_cat[0], 'product_cat' );
    $parent_cat_name = $parent_cat_term->name;
    $parent_cat_id = $parent_cat_term->term_id;
    
    /** CHILD **/ 
    if ( $current_category->parent != 0 ) {
        $child_cat_ids = get_term_children( $current_category->parent, 'product_cat' );
    
    /** DISPLAY PARENT **/ 
            if (!empty($parent_cat_id))/** Avoid error when no parent **/{
            echo '<a href="' . get_term_link( $parent_cat_id, 'product_cat' ) . '">' . $parent_cat_name . '</a>';           
            }
    /** DISPLAY CHILDS **/ 
            foreach ( $child_cat_ids as $child_cat_id ) {
                if( $child_cat_id != $current_category->term_id ) {
                    $child_cat_term = get_term_by( 'id', $child_cat_id, 'product_cat' );
                    echo '<a href="' . get_term_link( $child_cat_id, 'product_cat' ) . '">' . $child_cat_term->name . '</a>';
                }
            }
    }
相关问题