首页 文章

列出Woocommerce中给定产品类别的子类别

提问于
浏览
1

我在网上找到了各种片段列出了woocommerce产品类别,但我找不到列出给定类别的子类别和子子类别的片段 .

如何获得给定产品类别的子类别?

2 回答

  • 1

    这可以通过自定义函数在其中设置“父”产品类别slug:

    function get_product_subcategories_list( $category_slug ){
        $terms_html = array();
        $taxonomy = 'product_cat';
        // Get the product category (parent) WP_Term object
        $parent = get_term_by( 'slug', $category_slug, $taxonomy );
        // Get an array of the subcategories IDs (children IDs)
        $children_ids = get_term_children( $parent->term_id, $taxonomy );
    
        // Loop through each children IDs
        foreach($children_ids as $children_id){
            $term = get_term( $children_id, $taxonomy ); // WP_Term object
            $term_link = get_term_link( $term, $taxonomy ); // The term link
            if ( is_wp_error( $term_link ) ) $term_link = '';
            // Set in an array the html formated subcategory name/link
            $terms_html[] = '<a href="' . esc_url( $term_link ) . '" rel="tag" class="' . $term->slug . '">' . $term->name . '</a>';
        }
        return '<span class="subcategories-' . $category_slug . '">' . implode( ', ', $terms_html ) . '</span>';
    }
    

    代码位于活动子主题(或活动主题)的function.php文件中 .

    经过测试和工作 .


    Usage example:

    echo get_product_subcategories_list( 'clothing' );
    

    您将获得该给定类别的所有子类别的水平昏迷分隔列表(带有链接)

  • 1

    This is the code for get subcategory of given category:

    $categories = get_the_terms( get_the_ID(), 'product_cat' ); 
    
     //For checking category exit or not
    
     if ( $categories && ! is_wp_error( $category ) ) : 
    
    
       foreach($categories as $category) :
          // get the children (if any) of the current cat
          $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
    
        if ( count($children) == 0 ) {
           // if no children, then echo the category name.
            echo $category->name;
        }
      endforeach;
    
     endif;
    

相关问题