how to create optgroup of taxonomy list

    We can do this by using form_alter on the taxonomy form field like this :
    <?php
    if (isset($form['taxonomy'][$vid])) {
    $tree = taxonomy_get_tree($vid);
     
    $parent = array();
     
    $term_options[''] = $form['taxonomy'][$vid]['#options'][''];
      foreach (
    $tree as $term) {
       
    $obj = new stdClass();
       
    $obj->option[$term->tid] = $term->name;
      
        if(
    $ptid = $term->parents[0]) {
         
    $term_options[$parent[$ptid]][] = $obj;
        } else {
         
    $parent[$term->tid] = $term->name;
         
    $term_options[$term->name] = array();
        }
      
      }
     
    $form['taxonomy'][$vid]['#options'] = $term_options;
    }
    ?>
    Or If there is only one vocabulary associated then
    <?php
    if (isset($form['taxonomy'])) {
    $tree = taxonomy_get_tree($vid);
     
    $parent = array();
     
    $term_options[''] = $form['taxonomy']['#options'][''];
      foreach (
    $tree as $term) {
       
    $obj = new stdClass();
       
    $obj->option[$term->tid] = $term->name;
      
        if(
    $ptid = $term->parents[0]) {
         
    $term_options[$parent[$ptid]][] = $obj;
        } else {
         
    $parent[$term->tid] = $term->name;
         
    $term_options[$term->name] = array();
        }
      
      }
     
    $form['taxonomy']['#options'] = $term_options;
    }
    ?>
    4
    Average: 4 (1 vote)