List all the subcategories of a parent categoriey

I want to list all subcategories for a particular parent category in WordPress, I am new in PHP so I need some help any help would be rally appreciate, I want something like below code

<h2>Maine Category 1</h2>

<div class="row">
<div class="col">Subcategory 1</div>
<div class="col">Subcategory 2</div>
</div>

<div class="row">
<div class="col">Subcategory 3</div>
<div class="col">Subcategory 4</div>
</div>

<div class="row">
<div class="col">Subcategory 5</div>
<div class="col">Subcategory 6</div>
</div>

Related posts

2 comments

  1. Try this
    NOTE : 15 is your parent category id .

    $args = array('child_of' => 15);
    $categories = get_categories( $args );
    foreach($categories as $category) { 
        echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
        echo '<p> Description:'. $category->description . '</p>';
        echo '<p> Post Count: '. $category->count . '</p>';  
    }
    
  2. You can use wp_list_categories.

    Sample:

    $parentcat = $i;//category id
    wp_list_categories("depth=2&child_of=" . $parentcat . "&title_li=");

    or you can Try this in another process.

    <?php 
    $cat_id = get_query_var('cat');
    
    if( ! empty( $cat_id ) ) {
       $category = get_category( $cat_id, ARRAY_A );
    
      if( ! empty( $category ) ) {
         // parent category
         if( $category['parent'] === '0' ) {
    
            // get child IDs
            $terms = get_term_children( $cat_id, 'category' );
    
            foreach( $terms as $term_id ) {
                $child_category = get_term( $term_id, 'category' );
    
                // if you need the category
                $category_name = $child_category->name;
    
    
    
    
                // do whatever you like with the categories now...
                 echo '<p>Category: <a href="' . get_category_link( $child_category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $child_category->name ) . '" ' . '>' . $child_category->name.'</a> </p> ';
        }
    
    } else { 
    // in child category
        // do the regular loop here, if ( have_posts() ) ...
      }
     }
    }
    ?>
    

    also it’s posted Here

    hope it can help you 🙂

Comments are closed.