Reputation:
I am trying to get subcategory of current category using wp_dropdown_categories
.
onclick of category, i want to get subcategory. I did try using get_categories
function with arguments but it's not giving me subcategories. While using has_children
is giving me blank array.
This is my code:
add_action( 'wp_ajax_wp_get_subcategory', 'wp_get_subcategory' );
function wp_get_subcategory() {
$parent_cat_ID = $_POST['selected_category'];
$args = array(
'child_of' => $parent_cat_ID,
'taxonomy' => 'download_category',
'hide_empty' => 0,
'hierarchical' => false,
'depth' => 1,
'parent' => $parent_cat_ID
);
if ( isset($parent_cat_ID) ) {
$has_children = get_categories($args);
if ( $has_children ) {
//wp_dropdown_categories($args);
foreach ($has_children as $category) {
$option = '<option value="'.$category->cat_ID.'">';
$option .= $category->cat_name;
echo $option .= '</option>';
}
} else {
?><select name="sub_cat_disabled" id="sub_cat_disabled" disabled="disabled"><option>No child categories!</option></select><?php
}
die();
}
}
Upvotes: 1
Views: 1301
Reputation:
That's best if you are getting categories now, as far as your older code looks there is one minor mistake that's why your categories are not showing properly. Just change your
'hierarchical' => false,
to
'hierarchical' => true,
and so, your categories will be showing up nicely.
Upvotes: 1
Reputation: 991
Try this two example i have take this from some reference website. I hope this may useful to you
List subcategories if viewing a Category, and brothers / sibling categories if in subcategory.
<?php
if (is_category()) {
$this_category = get_category($cat);
}
?>
<?php
if($this_category->category_parent)
$this_category = wp_list_categories('orderby=id&show_count=0
&title_li=&use_desc_for_title=1&child_of='.$this_category->category_parent."&echo=0");
else $this_category = wp_list_categories('orderby=id&depth=1&show_count=0
&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID. "&echo=0");
if ($this_category) { ?>
<ul>
<?php echo $this_category; ?>
</ul>
<?php } ?>
Suppose the category whose subcategories you want to show is category 10, and that its category “nicename” is “archives”.
<select name="event-dropdown">
<option value=""><?php echo esc_attr_e( 'Select Event', 'textdomain' ); ?></option>
<?php
$categories = get_categories( array( 'child_of' => 10 );
foreach ( $categories as $category ) {
printf( '<option value="%1$s">%2$s (%3$s)</option>',
esc_attr( '/category/archives/' . $category->category_nicename ),
esc_html( $category->cat_name ),
esc_html( $category->category_count )
);
}
?>
</select>
For Reference: click me
Upvotes: 0