Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: Show only TOP level categories

Tags:

wordpress

I am using this bit of code:

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

$categories = get_categories($args);

What I am trying to do is to list only top level categories. When I am using this code I am getting all of them not just level one. Can someone help me?

like image 739
Ganikkost Avatar asked Feb 27 '13 13:02

Ganikkost


3 Answers

There is no depth argument for get_categories(), you should try :

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

parent : (integer) Display only categories that are direct descendants (i.e. children only) of the category identified by its ID. This does NOT work like the 'child_of' parameter. There is no default for this parameter. [In 2.8.4]

Read more : http://codex.wordpress.org/Function_Reference/get_categories#Get_only_top_level_categories

like image 174
soju Avatar answered Nov 15 '22 22:11

soju


soju post is very helpful, for to get category only 1 level subcategory we should just pass the category id that has subcategories . But if the subcategory have no any post then it doesnot shows but subcategory subcategory consist the post so add 'hide_empty' => 0, in the above condition it will look like

$args = array(
'taxonomy' => 'categories',
'parent' => 7,
'hide_empty' => 0,
);
like image 31
Bikram Shrestha Avatar answered Nov 15 '22 22:11

Bikram Shrestha


Here is my script to get top level category names from within the loop. This will include top level categories that just have a child category checked, and are not explicitly checked themselves.

<?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);
?>
like image 28
squarecandy Avatar answered Nov 15 '22 22:11

squarecandy