Skip to content

Instantly share code, notes, and snippets.

@dsebao
Last active February 26, 2021 15:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsebao/0db67e64259b558e727e to your computer and use it in GitHub Desktop.
Save dsebao/0db67e64259b558e727e to your computer and use it in GitHub Desktop.
Create OptGroups for select dropdown (categories) in WordPress using selectize plugin
<?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('&nbsp;', $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 .= '&nbsp;&nbsp;('. $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
)
);
?>
@ibazzocom
Copy link

Works perfectly
Just a litle note: with latest versions of Wordpress, the end_el() should have default parameters values and the fourth one should be like so:

function end_el(&$output,$object,$depth=0, $args = []) {
     if (0 == $depth/* && true == $this->optgroup*/) {
	 $output .= '</optgroup>';
      }
}

@dsebao
Copy link
Author

dsebao commented Dec 1, 2020

Perfect! Thanks @iBazzo i edited the snipppet

@ibazzocom
Copy link

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:

$output .= "<option class=\"level-$depth\" value=\"".$category->{$args['value_field']}."\"";
         
if ( $category->{$args['value_field']} == $args['selected'] ) {
     $output .= ' selected="selected"';
}

and again thanks @dsebao for the useful snippet
hope this helps some one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment