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

时间:2017-12-30 14:22:01

标签: php wordpress woocommerce categories product

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

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

2 个答案:

答案 0 :(得分:1)

这是给定类别的获取子类别的代码:

 $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;

答案 1 :(得分:1)

使用自定义功能可以设置“父”产品类别slug:

tx.origin

代码放在活动子主题(或活动主题)的function.php文件中。

经过测试和工作。

用法示例:

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>';
}

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