0

How can I get a subcategory name based on a category name in a WordPress post?

For example, consider 'volume' is the parent category. It has child categories like section1, section2, section3, etc. Then, section2 has another child category like article1, article2, etc.

In other words, the tree structure looks like this:

  • volume
    • section1
    • section2
      • article1
      • article2
    • section3

I want to get the section1, section2, section3 etc. names by 'volume', and I also want to get article1, article2 etc. by section2.

How can I do this?

0

If you want to get all the descendents for the volume category and its ID is lets say 5:

$categories = get_categories( array(
                'child_of' => 5
              ));
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>';  
}
  • You can also use get_term(). $terms = get_terms( 'Volume' ); – Annapurna Aug 19 '16 at 7:05
  • If I get it right form the docs child_of will retrieve all children recursively and parent is the argument to use for direct children only, as question requests. – Rarst Aug 19 '16 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.