Skip to content

Instantly share code, notes, and snippets.

@jeffreyvr
Last active February 8, 2018 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffreyvr/72a947bc5e363f037b16c58f226d94d9 to your computer and use it in GitHub Desktop.
Save jeffreyvr/72a947bc5e363f037b16c58f226d94d9 to your computer and use it in GitHub Desktop.
Make option groups from WordPress API Categories list
var categories = getCategories(); // this function gets the categories with ajax (you'll have to do that yourself ;-))
var html = "";
var tpl_categories = []; // top level categories
var top_cat_count = 0;
for (i = 0; i < categories.length; i++) {
if ( categories[i].parent == 0 ) {
tpl_categories[top_cat_count] = categories[i];
var sub_cat_count = 0;
for (sub_i = 0; sub_i < categories.length; sub_i++) {
if ( categories[sub_i].parent == categories[i].id ) {
if ( "sub_categories" in tpl_categories[top_cat_count] == false ) {
tpl_categories[top_cat_count].sub_categories = [];
}
tpl_categories[top_cat_count].sub_categories[sub_cat_count] = categories[sub_i];
sub_cat_count++;
}
}
top_cat_count++;
}
}
for (i = 0; i < tpl_categories.length; i++) {
if ( "sub_categories" in tpl_categories[i] ) {
html += '<optgroup label="'+tpl_categories[i].name+'">';
for ( sub_i = 0; sub_i < Object.keys(tpl_categories[i].sub_categories).length; sub_i++ ) {
html += '<option value="'+tpl_categories[i].sub_categories[sub_i].id+'">'+tpl_categories[i].sub_categories[sub_i].name+'</option>';
}
html += '</optgroup>';
} else {
html += '<option value="'+tpl_categories[i].id+'">'+tpl_categories[i].name+'</option>';
}
}
//console.log(html);
//$('select').html(html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment