I want to display categories and if the category is selected then display parent’s sub categories… I know there is some thread about this question but none of them fit to my problem.
I did 2 functions:
—- one for get all categories —-
function get_cats() {
$args = array('posts_per_page' => '-1',
'post_type' => 'cust_categories',
'post_status' => 'publish',
'suppress_filters' => false
);
$cust_query = get_posts($args);
if (!empty($cust_query)) {
$counter = 0;
foreach ($cust_query as $key => $dir) {
$selected = '';
if (intval($dir->ID) === intval($current)) {
$selected = 'selected';
}
echo '<option ' . $selected . ' value="' . $dir->ID . '">' . get_the_title($dir->ID) . '</option>';
}
}
}
—- one for get all sub categories —
function get_subcat($category) {
$parent_category_ID = $category->term_id;
$args = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $parent_category_ID,
'taxonomy' => 'sub_category'
);
$subcategories = get_categories($args);
foreach ($subcategories as $subcategory) {
$link = get_term_link( $subcategory->slug, $subcategory->taxonomy );
echo '<option value="'.$link.'">'.$subcategory->name.'</option>';
}
}
And I did a form which displays them in a dropdown:
<div class="form">
<label for="category" class="formlabel">Category</label>
<div class="fieldcontainer">
<select name="category" id="category">
<?php echo get_cats(); ?>
</select>
</div>
</div>
<div class="form">
<label for="sub_category" class="formlabel">Sub Category</label>
<div class="fieldcontainer">
<select name="sub_category" id="sub_category">
<option value="">Select</option>
<?php echo get_subcat('sp_categories'); ?>
</select>
</div>
</div>
Everything works fine but I want to display the selected category’s (parent’s) sub category only in the sub category dropdown, how can I achieve this?