Get a list of subcategories

I have this category on my Wordpress:

Test1 - Sub1OfTest1 - Sub2OfTest1 Test2 - Sub1OfTest2 - Sub2OfTest2 

Now iam in the URL: http://localhost/wordpress/category/test1 I am writing the following code in the category-test1.php

 <?php $categories = get_categories('child_of=2'); print_r($categories); foreach ($categories as $category) : ?> <div class="qitem"> <a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>"> <?php echo $category->name; ?> </a> <h4> <span class="caption"> <?php echo $category->name; ?> </span> </h4> <p> <span class="caption"> <?php echo $category->description; ?> </span> </p> </div> <?php endforeach; ?> 

I am trying to show a subcategory of Test1, but the code only returns an array (). What did I miss?

+4
source share
4 answers

Is this category empty? By default, WordPress hides emptr categories. try:

 $categories = get_categories('child_of=2&hide_empty=0'); 

Edit: Fixed, thanks @Stoep

+8
source

The child_of argument child_of indicates the category by its identifier - provided that you created your categories in order, the code get_categories('child_of=2') probably asks for subcategories Sub1OfTest1.

To get the category ID, go to Posts → Categories and click on the category. Cat_ID will be in the URL of the page.

0
source

try it too - only show subcategories of Wordpress

this topic may help, as there are various solutions for showing subcategories.

0
source

// This is the coding for getting the subcategory and subcategory

  $args = array ( 'number' => $number, 'orderby' => 'title', 'order' => 'ASC', 'hide_empty' => false, 'include' => array(11,281,28,51,99,93,33,55,107,20), 'exclude' => array(32,29), ); $product_categories = get_terms( 'product_cat', $args ); // echo '<pre>'; // print_r($product_categories); // echo '</pre>'; foreach($product_categories as $data): if($data->slug = 'cooking') { $child_arg = array('hide_empty'=>false,'parent'=>$data->term_id,'exclude'=>array(32,29)); } else { $child_arg = array('hide_empty'=>false,'parent'=>$data->term_id); } $child_terms = get_terms('product_cat',$child_arg); // echo "<pre>"; // print_r($child_terms); // echo "</pre>"; foreach($child_terms as $data1): if($data1->slug = 'cooking') { $sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id,'exclude'=>array(32,29)); } else { $sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id); } $sub_child_terms = get_terms('product_cat',$sub_child_arg); // echo "<pre>"; // print_r($sub_child_terms); // echo "</pre>"; endforeach; endforeach; ?> 
0
source

All Articles