11

我正在使用这段代码:

$args = array(
  'orderby' => 'name',
  'hierarchical' => 1,
  'style' => 'none',
  'taxonomy' => 'category',
  'hide_empty' => 0,
  'depth' => 1,
  'title_li' => ''
);

$categories = get_categories($args);

我想做的是只列出顶级类别。当我使用这段代码时,我得到的不仅仅是一级。有人能帮我吗?

4

4 回答 4

30

没有depth论据get_categories(),您应该尝试:

$args = array(
  'orderby' => 'name',
  'parent' => 0
);

parent: (integer) 仅显示由其 ID 标识的类别的直接后代(即仅限子项)的类别。这不像 'child_of' 参数那样工作。此参数没有默认值。[在 2.8.4 中]

阅读更多:http ://codex.wordpress.org/Function_Reference/get_categories#Get_only_top_level_categories

于 2013-02-27T13:42:56.777 回答
2

soju post 非常有用,因为要获得仅 1 级子类别的类别,我们应该只传递具有 subcategories 的类别 id。但是如果子类别没有任何帖子那么它不会显示但子类别子类别包含帖子所以添加'hide_empty' => 0,在上述情况下它看起来像

$args = array(
'taxonomy' => 'categories',
'parent' => 7,
'hide_empty' => 0,
);
于 2013-08-22T17:51:43.467 回答
2

这是我从循环中获取顶级类别名称的脚本。这将包括仅检查了子类别且自身未明确检查的顶级类别。

<?php
    $categories = get_the_category();
    $topcats = array();
    foreach ($categories as $cat) {
        if ($cat->parent != 0) $cat = get_term($cat->parent, 'category');
        $topcats[$cat->term_id] = '<a href="/category/' . $cat->slug . '">' . $cat->name . '</a>';
    }
    echo implode(', ', $topcats);
?>
于 2017-04-23T03:16:34.900 回答
0

此功能允许您选择哪个类别级别......所以在您的情况下,您可以选择级别 0,它看起来像<?php display_cat_level(0,true); ?>您的 single.php 主题文件

https://github.com/pjeaje/code-snippets/blob/gh-pages/display%20a%20specific%20category%20level%20of%20a%20post%20inside%20the%20loop

// http://wpquestions.com/question/showChronoLoggedIn/id/9333
// display a specific category level of a post inside the loop
// USAGE: <?php display_cat_level(X,true); ?> where TRUE = linked | false/empty = not linked
function get_level($category, $level = 0)
{
    if ($category->category_parent == 0) {
        return $level;
    } else {
        $level++;
        $category = get_category($category->category_parent);
        return get_level($category, $level);
    }
}

function display_cat_level( $level = 0 , $link=false){

    $cats = get_the_category( );
    if( $cats ){
        foreach($cats as $cat){
            $current_cat_level = get_level($cat);
            if( $current_cat_level  == $level ){
                if($link==true) {
                    echo '<a href="'.get_category_link($cat->cat_ID).'">'.$cat->name."</a><br />";
                } else {
                    echo $cat->name."<br />";
                }
            }
        }
    }
}
于 2019-09-21T13:41:12.353 回答