在WooCommerce中显示子类别

时间:2015-12-03 作者:Peyton Gregory

此代码显示WooCommerce产品类别的两个父类别的类别缩略图和标题。

我还想显示几个子类别。是否有办法显示所有类别或选择要显示的类别ID?

$taxonomyName = "product_cat";
$prod_categories = get_terms( $taxonomyName, array(
    \'orderby\'    => \'name\',
    \'order\'      => \'ASC\',
    \'hide_empty\' => -1
) );  
foreach( $prod_categories as $prod_cat ) :
    if ( $prod_cat->parent != 0 )
        continue;
    $cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, \'thumbnail_id\', true );
    $cat_thumb_url = wp_get_attachment_thumb_url( $cat_thumb_id );
    $term_link = get_term_link( $prod_cat, \'product_cat\' );
    ?><img  src="<?php echo $cat_thumb_url; ?>" alt="" /> 
    <a class="button" href="<?php echo $term_link; ?>"> <?php echo $prod_cat->name; ?> </a>
<?php endforeach; 
wp_reset_query();

1 个回复
SO网友:Pankaj Sharma

以下是您问题的解决方案:请检查此项,我希望它将帮助您显示子类别详细信息。

  $taxonomy     = \'product_cat\';
  $orderby      = \'name\';
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no
  $title        = \'\';
  $empty        = 0;

  $args = array(
         \'taxonomy\'     => $taxonomy,
         \'orderby\'      => $orderby,
         \'show_count\'   => $show_count,
         \'pad_counts\'   => $pad_counts,
         \'hierarchical\' => $hierarchical,
         \'title_li\'     => $title,
         \'hide_empty\'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        echo \'<br /><a href="\'. get_term_link($cat->slug, \'product_cat\') .\'">\'. $cat->name .\'</a>\'; ?>

        $args2 = array(
                \'taxonomy\'     => $taxonomy,
                \'child_of\'     => 0,
                \'parent\'       => $category_id,
                \'orderby\'      => $orderby,
                \'show_count\'   => $show_count,
                \'pad_counts\'   => $pad_counts,
                \'hierarchical\' => $hierarchical,
                \'title_li\'     => $title,
                \'hide_empty\'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                 echo  $sub_category->name ;
                 $thumbnail_id = get_woocommerce_term_meta( $sub_category->term_id, \'thumbnail_id\', true );
                 $image = wp_get_attachment_url( $thumbnail_id );
                 echo  \'<img src="\'.$image.\'" alt="" height="20" width="20">\';
                //add other code here to display child details

            }   
        }
    }       
}