• Hello,

    I am very new to WordPress as well as coding and I am stuck with one of the form field, which has a select box for listing all categories and sub-categories (taxonomies) in it. But I would like a seperate select box for displaying sub-categories for the selected category dynamically.

    Below is the code in functions.php:

    function mytheme_get_categories($taxo, $selected = "", $include_empty_option = "", $ccc = "")
    {
    	$args = "orderby=name&order=ASC&hide_empty=0&parent=0";
    	$terms = get_terms( $taxo, $args );
    
    	$ret = '<select name="'.$taxo.'_cat" class="'.$ccc.'" id="'.$ccc.'">';
    	if(!empty($include_empty_option)) $ret .= "<option value=''>".$include_empty_option."</option>";
    
    	if(empty($selected)) $selected = -1;
    
    	foreach ( $terms as $term )
    	{
    		$id = $term->term_id;
    
    		$ret .= '<option '.($selected == $id ? "selected='selected'" : " " ).' value="'.$id.'">'.$term->name.'</option>';
    
    		$args = "orderby=name&order=ASC&hide_empty=0&parent=".$id;
    		$sub_terms = get_terms( $taxo, $args );	
    
    		if($sub_terms)
    		foreach ( $sub_terms as $sub_term )
    		{
    			$sub_id = $sub_term->term_id;
    			$ret .= '<option '.($selected == $sub_id ? "selected='selected'" : " " ).' value="'.$sub_id.'">&nbsp; &nbsp;|&nbsp;  '.$sub_term->name.'</option>';
    		}
    
    	}
    
    	$ret .= '</select>';
    
    	return $ret;
    
    }

    and the code in post_new.php is as below:

    <li><h2><?php echo __('Category', 'mytheme'); ?>:</h2>
            	<p><?php	echo mytheme_get_categories("ad_cat",
    			!isset($_POST['ad_cat_cat']) ? (is_array($cat) ? $cat[0]->term_id : "") : $_POST['ad_cat_cat']
    			, __("Select Category","mytheme"), "do_input"); ?></p>
    </li>
    <?php do_action('mytheme_after_category_li'); ?>

    Any help is much appreciated as I have been trying to do this for over a week now.

    Thank you.

  • The topic ‘Seperate select box for sub-categories for selected category’ is closed to new replies.