Reputation: 103
I am building a real estate website so i have many category 3 to 4 level child category but my requirement is to show only one level sub category of the parent category eg sub1 ,sub2 and sub3 only see the structure I'm having category like this
- cat1
- sub1
- secondsub1
- cat2
- sub2
- secondsub2
- cat3
- sub3
- secondsub3
$categories = get_terms(
'category',
array('hide_empty' => 0,'parent' => 0,'number' =>3,'order'=> 'ASC')
);
foreach ($categories as $category) {
$catName= $category->term_id;
<?php echo get_cat_name( $catName ); // this is the main category ?>
<!-- subcategory code starts here-->
$args = array(
'type' => 'post',
'child_of' => $catName,
'parent' => get_query_var(''),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '5',
'taxonomy' => 'category',
'pad_counts' => true );
$categories = get_categories($args);
foreach($categories as $category) {
<a href="<?php echo get_category_link( $category->term_id )?>" title="View posts in <?php echo $category->name?>"><?php $category->name;?></span><!--these are the sub category-->
}
}
In result i get under cate1 sub1->secondsub1 because secondsub1 is also child to cat1 but i only want sub1 how can i accomplish that ? any suggestions
Upvotes: 2
Views: 2699
Reputation: 787
You could use wp_list_categories( (Developer Wordpress Reference) to get subcategories for each of your category. Im not sure about efficiency of this usage, but give it a try.
So in your code that would be here:
<!-- subcategory code starts here-->
wp_list_categories( array(
'child_of' => $category->term_id,
'depth' => 1
) );
After some reading I found other solution, so you would use:
$args = array('parent' => $category->term_id);
$categories = get_categories( $args );
foreach($categories as $category) {
<a href="<?php echo get_category_link( $category->term_id )?>" title="View posts in <?php echo $category->name?>"><?php $category->name;?></span><!--these are the sub category-->
}
Also take care with using '$categories' twice, this may get a little bit confusing.
Upvotes: 2
Reputation: 3816
Use parent
instead of child_of
:
parent
(int|string) Parent term ID to retrieve direct-child terms of.
Source: #parameters
Upvotes: 4