[wp-trac] [WordPress Trac] #33841: WP_Dropdown_Categories: Parent Category Optgroups
WordPress Trac
noreply at wordpress.org
Sat Sep 12 11:14:04 UTC 2015
#33841: WP_Dropdown_Categories: Parent Category Optgroups
-------------------------+-----------------------------
Reporter: tifosi | Owner:
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Taxonomy | Version: trunk
Severity: normal | Keywords:
Focuses: |
-------------------------+-----------------------------
On a number of occasions I've structured a hierarchical taxonomy with
parent > child categories, but have only wanted to be able to select the
child categories. An example of this is country > county, or manufacturer
> model.
The best way to do this is to set the parent category as an optgroup.
wp_dropdown_categories() doesn't handle this through the
Walker_CategoryDropdown class.
I would like a new option for the wp_dropdown_categories() function
arguments to enable this, for example:
parent_optgroup = true (default, false)
This could either trigger a flow change in the walker class, or the use of
an extended class. I'm currently using an override to the walker argument
to the function - the codex doesn't advertise this is available, but
works:
{{{
$args = array(
....
'hierarchical' => 1,
'taxonomy' => $taxonomy,
'walker' => new Walker_CategoryDropdown_Optgroup
);
wp_dropdown_categories( $args );
}}}
{{{
/**
* Parent level optgroup walker extension
*/
class Walker_CategoryDropdown_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);
// set parent optgroup
if (0 == $depth) {
$this->optgroup = true;
$output .= '<optgroup class="level-$depth" label="' .
$cat_name . '" >';
} else {
$this->optgroup = false;
$output .= '<option class="level-' . $depth. '" value="' .
$category->term_id . '"';
if ( $category->term_id == $args['selected'] ) {
$output .= ' selected="selected"';
}
$output .= '>' . $pad.$cat_name;
if ( $args['show_count'] ) {
$output .= ' ('. $category->count .')';
}
$output .= "</option>";
}
}
function end_el( &$output, $object, $depth = 0, $args = array() ) {
if ( 0 == $depth && true == $this->optgroup ) {
$output .= '</optgroup>';
}
}
}
}}}
This sets the parent term (depth 0) as an optgroup, and all child elements
are left as standard select options.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/33841>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list