【问题标题】:How to show only one level sub category?如何只显示一个级别的子类别?
【发布时间】:2017-03-24 05:01:43
【问题描述】:

我正在建立一个房地产网站,所以我有很多 3 到 4 类 级别子类别,但我的要求是只显示一个级别子 父类别的类别,例如 sub1 ,sub2 和 sub3 只看到我拥有的结构这样的类别

- cat1
    - sub1
       - secondsub1
- cat2
    - sub2
      - secondsub2
- cat3
   - sub3
      - secondsub3



$categories = get_terms(
                    'category', 
                    array('hide_empty' => 0,'parent' => 0,'number' =>3,'order'=> 'ASC') 
                        );
foreach ($categories as $category) {
            $catName= $category->term_id;

<?php echo get_cat_name( $catName ); // this is the main category ?>

<!-- subcategory code starts here-->

        $args = array(
                    'type' => 'post',
                    'child_of' => $catName,
                    'parent' => get_query_var(''),
                    'orderby' => 'name',
                    'order' => 'ASC',
                    'hide_empty' => 0,
                    'hierarchical' => 1,
                    'exclude' => '',
                    'include' => '',
                    'number' => '5',
                    'taxonomy' => 'category',
                    'pad_counts' => true );
                    $categories = get_categories($args);
                    foreach($categories as $category) {
<a href="<?php echo get_category_link( $category->term_id )?>" title="View posts in <?php echo $category->name?>"><?php $category->name;?></span><!--these are the sub category-->
 }
}

结果我得到了 cate1 sub1->secondsub1 因为 secondsub1 也是 cat1 的孩子,但我只想要 sub1 我怎么能做到这一点?任何建议

【问题讨论】:

    标签: php wordpress categories


    【解决方案1】:

    您可以使用 wp_list_categories( (Developer Wordpress Reference) 来获取每个类别的子类别。我不确定这种用法的效率,但请尝试一下。

    所以在你的代码中:

    <!-- subcategory code starts here-->
    wp_list_categories( array(
        'child_of'    => $category->term_id,
        'depth'       => 1    
    ) );
    

    经过一番阅读,我找到了其他解决方案,因此您可以使用:

        $args = array('parent' => $category->term_id);
        $categories = get_categories( $args );
        foreach($categories as $category) { 
            <a href="<?php echo get_category_link( $category->term_id )?>" title="View posts in <?php echo $category->name?>"><?php $category->name;?></span><!--these are the sub category-->
        }
    

    还要注意两次使用“$categories”,这可能会让人有点困惑。

    【讨论】:

    • 感谢您的回答,但我不想使用您提供的 wp_list_categories 第二个答案,谢谢:)
    【解决方案2】:

    使用parent 代替child_of:

    parent (int|string) 用于检索直接子项的父项 ID。

    来源:#parameters

    【讨论】:

    • 感谢您的回答,我只是忘了我不应该使用 child_of :)
    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2019-03-31
    相关资源
    最近更新 更多