Last active
February 26, 2021 15:00
-
-
Save dsebao/0db67e64259b558e727e to your computer and use it in GitHub Desktop.
Create OptGroups for select dropdown (categories) in WordPress using selectize plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Top_level_Optgroup extends Walker_CategoryDropdown { | |
var $optgroup = false; | |
function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) { | |
$pad = str_repeat(' ', $depth * 3); | |
$cat_name = apply_filters('list_cats', $category->name, $category); | |
if (0 == $depth) { | |
// $this->optgroup = true; | |
$output .= "<optgroup class=\"level-$depth\" label=\"".$cat_name."\" >"; | |
} else { | |
$output .= "<option class=\"level-$depth\" value=\"".$category->term_id."\""; | |
if ( $category->term_id == $args['selected'] ) | |
$output .= ' selected="selected"'; | |
$output .= '>'; | |
$output .= $pad.$cat_name; | |
if ( $args['show_count'] ) | |
$output .= ' ('. $category->count .')'; | |
$output .= "</option>"; | |
} | |
} | |
function end_el(&$output,$object,$depth=0, $args = []) { | |
if (0 == $depth/* && true == $this->optgroup*/) { | |
$output .= '</optgroup>'; | |
} | |
} | |
} | |
// usage test | |
wp_dropdown_categories( | |
array( | |
'orderby' => 'name', | |
'hide_empty' => 0, | |
'show_count' => 1, | |
'show_option_none' => 'Select one', | |
'class' => 'cat', | |
'hierarchical' => 1, | |
'name' => 'cat', | |
'walker' => new Top_level_Optgroup | |
) | |
); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another little improvment..
$output .= "<option class=\"level-$depth\" value=\"".$category->term_id."\"";
with this code we assume that the value should be always the category ID, but in some cases we would want the option value to be what ever we put un the argument "value_field" passed to wp_dropdown_categories()
so, it would be better to set it dynamically, according to user $args put to the function, like this:
and again thanks @dsebao for the useful snippet
hope this helps some one