Full Stop
Full Stop

Reputation: 853

Display only first level child subcategory in wordpress

Here is my question example :

monitor (Main category)

Here is my code:

$term_id = $catid;
$taxonomy_name = 'providers-category';
$term_children = get_term_children( $term_id, $taxonomy_name );

if(count($term_children) > 0){

    echo '<div class="container"><div class="checkboxes"><ul>';
foreach ( $term_children as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    echo '<li> <input class="chk_child_cat" type="checkbox" value="1" data-id="'. get_term_link( $child, $taxonomy_name ).'"/><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul></div></div>';
}else{
 echo '<div><h2><b>Opps!...Sub category not found.<b></h2></div>';
}

Upvotes: 2

Views: 3079

Answers (1)

Niket Joshi
Niket Joshi

Reputation: 748

I have added this snippets which one is fully tested from my side and also used this in my projet too.

$term_id = $catid; /* Assume that here is your parent ID */
$taxonomy_name = 'providers-category'; /* Want child of the parent category */
 $args = array(
              'hide_empty' => 0,
              'orderby' => 'name',
              'depth' => 1,
              'parent' => $term_id,
              'order' => 'ASC',
              'taxonomy' => 'providers-category'
          );
  $term_children = get_categories($args);
   foreach ( $term_children as $child ) {
  ?>
          <li class="city-item"><a href="<?php  echo get_term_link( $child, $taxonomy_name )   ?>"><?php echo $child->name;  ?></a></li>
  <?php } ?>

You can customize this as your project requirement i just give you idea to fetch child category base on Parent ID.

Thanks Hope this works for you.

Upvotes: 8

Related Questions