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();
}
}
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
to
and so, your categories will be showing up nicely.
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.
Suppose the category whose subcategories you want to show is category 10, and that its category ânicenameâ is âarchivesâ.
For Reference: click me