Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

get_terms() to show children under parent WordPress



I have a widget showing a list of custom taxonomy "Job Categories" in my side bar, using the below code : -

$args = array(
'hierarchical' => false,
'parent' => 0
$terms = get_terms( 'job_cat', $args );
if ($terms) :
echo '<li><a class="top" href="#open">'.__('Job Category', 'appthemes').'</a> <ul>';

foreach($terms as $term) :
echo '<li class="page_item ';
if ( isset($wp_query->queried_object->slug) && $wp_query->queried_object->slug==$term->slug ) echo 'current_page_item';
echo '"><a href="'.get_term_link( $term->slug, 'job_cat' ).'">'.$term->name.'</a></li>';

echo '</ul></li>';

I want it to also show any child categories but under their parent category and in a way that I can target them to indent them slightly with CSS. I can get them all to show by removing the 'parent' => 0 argument, but then they are not with their parent and just all jumbled together.

I attach an image of the sidebar which currently just shows the parent cats incase that helps.

Thanks in advance!

Answers (3)


Pixel Coder answers:

Here's one way you could do it.

$args = array('hide_empty' => 0, 'orderby' => 'term_group');
$terms = get_terms('job_cat', $args);
if($terms) :
$output .= '<ul>';
$output .= '<li><a class="top" href="#open">'.__('Job Category', 'appthemes').'</a> <ul>';
foreach($terms as $term) :
if($parent = $term->parent) :
$class = 'child';
else :
$class = 'parent';
$output .= '<li class="'.$class.'"><a href="'.$term->slug.'">'.$term->name.'</a></li>';
$parent = $term->parent;
$output .= '</ul>';
echo $output;

This will only work 2 levels deep, if you wish to add a child of a child this would need a little more logic.

hide_empty is not required, you would pass your custom term arguments as normal here.

*edit, code updated for your term.

Jennie Routley comments:

This worked perfectly! Thank you.


Pixel Coder comments:

You are welcome, good luck.


juan manuel incaurgarat answers:

have you tried this?

<?php wp_list_categories('hierarchical=1&sort_column=name&title_li='); ?>

with this CSS:

ul.children{margin-left: 10px;}

more info here:

Jennie Routley comments:

Hi - they are not actual categories but custom taxonomies, so don't believe that would work. Thanks though, good suggestion, I should have been clearer.


Arnav Joy answers:

try this

<ul id="list">
$terms = get_terms('Job Categories',array('parent' => 0 , 'hide_empty'=> '0' ));
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
echo ' <li>'.$term->name.'</li>';
$terms1 = get_terms('Job Categories',array('parent' => $term->term_id , 'hide_empty'=> '0' ));
echo '<ul>';
foreach ($terms1 as $term1) {
echo ' <li><a href="'.get_category_link($term1->term_id).'">'.$term1->name.'</a></li>';
echo '</ul>';