Skip to content

Instantly share code, notes, and snippets.

@pdewouters
Created January 11, 2012 01:33
Show Gist options
  • Save pdewouters/1592415 to your computer and use it in GitHub Desktop.
Save pdewouters/1592415 to your computer and use it in GitHub Desktop.
suggestion for hierchical dropdown
case 'taxonomy_select':
$names= wp_get_object_terms( $post->ID, $field['taxonomy'] );
$terms = get_terms( $field['taxonomy'], 'hide_empty=0' );
$selected = '';
foreach ( $terms as $term ) {
if (!is_wp_error( $names ) && !empty( $names ) && !strcmp( $term->slug, $names[0]->slug ) ) {
$selected = $term->slug;
} else {
}
}
wp_dropdown_categories(array('selected' => $selected,'taxonomy' => $field['taxonomy'], 'hide_empty' => false, 'hierarchical' => 1, 'id' => $field['id'], 'name' => $field['id'],'walker' => new Mfields_Walker_Taxonomy_Dropdown() ));
echo '<p class="cmb_metabox_description">', $field['desc'], '</p>';
break;
//added this at the bottom of init.php
/* Custom version of Walker_CategoryDropdown */
class Mfields_Walker_Taxonomy_Dropdown extends Walker {
var $db_fields = array(
'id' => 'term_id',
'parent' => 'parent'
);
var $tree_type = 'category';
function start_el( &$output, $term, $depth, $args ) {
$selected_terms = array();
if ( isset( $args['selected'] ) ) {
$selected_terms = (array) $args['selected'];
}
$selected = '';
if ( in_array( $term->slug, $selected_terms ) ) {
$selected .= ' selected="selected"';
}
$text = str_repeat( '&nbsp;', $depth * 3 ) . $term->name;
if ( $args['show_count'] ) {
$text .= '&nbsp;&nbsp;(' . absint( $term->count ) . ')';
}
if ( $args['show_last_update'] ) {
$text .= '&nbsp;&nbsp;' . gmdate( __( 'Y-m-d', 'mfields-taxonomy-widget' ), $term->last_update_timestamp );
}
$class_name = 'level-' . $depth;
$output.= "\t" . '<option' . $selected . ' class="' . esc_attr( $class_name ) . '" value="' . $term->slug . '">' . esc_html( $text ) . '</option>' . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment