Skip to content

Instantly share code, notes, and snippets.

@elundmark
Created September 23, 2011 13:31
Show Gist options
  • Save elundmark/1237328 to your computer and use it in GitHub Desktop.
Save elundmark/1237328 to your computer and use it in GitHub Desktop.
Divide wp_dropdown_categories to include alphabetical optgroups
// put this in your functions.php file
function fixedCategoryDropdown() {
$categories = get_categories('depth=1');
$catcount = count($categories);
$categorymenu = wp_dropdown_categories(
array(
// See http://codex.wordpress.org/Function_Reference/wp_dropdown_categories
// for all the available options
// These are the ones that makes sence for this example
'orderby' => 'name',
'echo' => false,
)
);
// save some kb's by removing the level class name given by WP,
// if you only have one leveled categories - optional
//$categorymenu = preg_replace("#\sclass\=\"level\-0\"#","",$categorymenu);
// and some more bytes by removing   
//$categorymenu = html_entity_decode($categorymenu, ENT_COMPAT, 'UTF-8');
// Now, lets make some optgroup's!
$exploded_html = '<option';
$new_html_arr = array();
$options = explode($exploded_html, $categorymenu);
$new_html = array_shift($options).$exploded_html.array_shift($options);
for ($i=0; $i < sizeof($options); $i++) {
preg_match("#(\'|\")\>(\w)#i", $options[$i], $first_letter_match);
$first_letter = strtolower($first_letter_match[2]);
if ($i == 0) {
$new_html_arr[] = $first_letter;
$new_html_arr[] = $options[$i];
$current_letter = $first_letter;
} elseif ($current_letter == $first_letter) {
$new_html_arr[] = $options[$i];
} else {
$new_html_arr[] = $first_letter;
$new_html_arr[] = $options[$i];
$current_letter = $first_letter;
}
}
for ($i = 0; $i < sizeof($new_html_arr); $i++) {
if (strlen($new_html_arr[$i]) == 1) {
$new_html .= $i ? "</optgroup>" : "";
$new_html .= '<optgroup label="'.strtoupper($new_html_arr[$i]).'">';
} else {
$new_html .= $exploded_html.$new_html_arr[$i];
}
}
// Return the new html, call this function in your theme = ' echo fixedCategoryDropdown(); '
return $new_html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment