是否显示特定类别中的所有子类别?

时间:2013-05-30 作者:Yhis

我需要使用显示所有子类别

$product_category = wp_get_post_terms( $post->ID, \'product_cat\' );
实际上我使用:

<?php 

global $post;

$terms = get_the_terms( $post->ID, \'product_cat\', \'hide_empty=0\'  );
foreach ( $terms as $term ){
    $category_id = $term->term_id;
    $category_name = $term->name;
    $category_slug = $term->slug;

    echo \'<li><a href="\'. get_term_link($term->slug, \'product_cat\') .\'">\'.$category_name.\'</a></li>\';
}   

?>
没关系,但它只显示父类别和一个子类别。。。

如何解决这个问题?

2 个回复
最合适的回答,由SO网友:Nicolai Grossherr 整理而成

尝试以下操作:

按ID

function woocommerce_subcats_from_parentcat_by_ID($parent_cat_ID) {
    $args = array(
       \'hierarchical\' => 1,
       \'show_option_none\' => \'\',
       \'hide_empty\' => 0,
       \'parent\' => $parent_cat_ID,
       \'taxonomy\' => \'product_cat\'
    );
  $subcats = get_categories($args);
    echo \'<ul class="wooc_sclist">\';
      foreach ($subcats as $sc) {
        $link = get_term_link( $sc->slug, $sc->taxonomy );
          echo \'<li><a href="\'. $link .\'">\'.$sc->name.\'</a></li>\';
      }
    echo \'</ul>\';
}
按名称
function woocommerce_subcats_from_parentcat_by_NAME($parent_cat_NAME) {
  $IDbyNAME = get_term_by(\'name\', $parent_cat_NAME, \'product_cat\');
  $product_cat_ID = $IDbyNAME->term_id;
    $args = array(
       \'hierarchical\' => 1,
       \'show_option_none\' => \'\',
       \'hide_empty\' => 0,
       \'parent\' => $product_cat_ID,
       \'taxonomy\' => \'product_cat\'
    );
  $subcats = get_categories($args);
    echo \'<ul class="wooc_sclist">\';
      foreach ($subcats as $sc) {
        $link = get_term_link( $sc->slug, $sc->taxonomy );
          echo \'<li><a href="\'. $link .\'">\'.$sc->name.\'</a></li>\';
      }
    echo \'</ul>\';
}

Source/inspiration

Edit:

完成了代码,对其进行了测试,请参见注释

SO网友:Mike Langley

以下是在页面模板中为我工作的代码(我的父id为7):

<?php $wcatTerms = get_terms(\'product_cat\', array(\'hide_empty\' => 0, \'orderby\' => \'ASC\', \'parent\' => 7, )); 
        foreach($wcatTerms as $wcatTerm) : 
        $wthumbnail_id = get_woocommerce_term_meta( $wcatTerm->term_id, \'thumbnail_id\', true );
        $wimage = wp_get_attachment_url( $wthumbnail_id );
    ?>
    <div><a href="<?php echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>">
    <?php if($wimage!=""):?><img src="<?php echo $wimage?>" class="aligncenter"><?php endif;?></a>
    <h3 class="text-center"><a href="<?php echo get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ); ?>"><?php echo $wcatTerm->name; ?></a></h3>
    </div>
    <?php endforeach; ?> 

结束

相关推荐

get_terms on save_post hook

通常,如果我想检查即将发布的帖子的某些属性,我会这样检查:$post_title = $_POST[\'post_title\']; post\\u title是编辑窗口中标题字段的名称。我想我应该对分类法元框应用相同的逻辑。$formats = $_POST[\'tax_input[formats][]\']; 本质上,我试图检查在发布帖子时是否选择了特定的分类术语。