I am using the below code but just display parent categories while i have many child categories. I want to display all categories including parents and childs
<label for="<?php echo $this->get_field_id( 'link' ); ?>"><?php _e( 'دسته بندی' ); ?></label>
<select id="<?php echo $this->get_field_id('link'); ?>" name="<?php echo $this->get_field_name('link'); ?>" class="widefat" style="width:100%;">
<?php foreach(get_terms('category','parent=0&hide_empty=false') as $term) { ?>
<option <?php selected( $instance['link'], $term->term_id ); ?> value="<?php echo $term->term_id; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
I am using the below code but just display parent categories while i have many child categories. I want to display all categories including parents and childs
<label for="<?php echo $this->get_field_id( 'link' ); ?>"><?php _e( 'دسته بندی' ); ?></label>
<select id="<?php echo $this->get_field_id('link'); ?>" name="<?php echo $this->get_field_name('link'); ?>" class="widefat" style="width:100%;">
<?php foreach(get_terms('category','parent=0&hide_empty=false') as $term) { ?>
<option <?php selected( $instance['link'], $term->term_id ); ?> value="<?php echo $term->term_id; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
Share
Improve this question
asked May 27, 2019 at 7:28
m.javad koushkim.javad koushki
54 bronze badges
1 Answer
Reset to default 0The reason it's only getting parents is this part:
parent=0
This queries categories that don't have a parent, so you only get the top level. Remove it and you'll get all categories:
get_terms('category','hide_empty=false')
That being said, you'd be better off using wp_dropdown_categories()
. That way you will get the proper ordering and indentation of child categories:
<label for="<?php echo $this->get_field_id( 'link' ); ?>">
<?php _e( 'دسته بندی' ); ?>
</label>
<?php
wp_dropdown_categories(
[
'id' => $this->get_field_id( 'link' ),
'name' => $this->get_field_name( 'link' ),
'class' => 'widefat',
'selected' => $instance['link'],
]
);
?>