Last active
August 29, 2015 13:59
-
-
Save Ciantic/10784157 to your computer and use it in GitHub Desktop.
Shows the taxonomy selection in admin as <select> box
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 | |
| // Author: Jari Pennanen | |
| // License: Public Domain | |
| // 2014-04-16 | |
| /** | |
| * Display taxonomy selection in admin as select box | |
| * | |
| * @param WP_Post $post | |
| * @param array $box | |
| */ | |
| function my_admin_taxonomy_select_meta_box($post, $box) { | |
| $defaults = array('taxonomy' => 'category'); | |
| if (!isset($box['args']) || !is_array($box['args'])) | |
| $args = array(); | |
| else | |
| $args = $box['args']; | |
| extract(wp_parse_args($args, $defaults), EXTR_SKIP); | |
| $tax = get_taxonomy($taxonomy); | |
| $selected = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids')); | |
| $hierarchical = $tax->hierarchical; | |
| ?> | |
| <div id="taxonomy-<?php echo $taxonomy; ?>" class="selectdiv"> | |
| <?php if (current_user_can($tax->cap->edit_terms)): ?> | |
| <?php | |
| if ($hierarchical) { | |
| wp_dropdown_categories(array( | |
| 'taxonomy' => $taxonomy, | |
| 'class' => 'widefat', | |
| 'hide_empty' => 0, | |
| 'name' => "tax_input[$taxonomy][]", | |
| 'selected' => count($selected) >= 1 ? $selected[0] : '', | |
| 'orderby' => 'name', | |
| 'hierarchical' => 1, | |
| 'show_option_all' => " " | |
| )); | |
| } else { | |
| ?> | |
| <select name="<?php echo "tax_input[$taxonomy][]"; ?>" class="widefat"> | |
| <option value="0"></option> | |
| <?php foreach (get_terms($taxonomy, array('hide_empty' => false)) as $term): ?> | |
| <option value="<?php echo esc_attr($term->slug); ?>" <?php echo selected($term->term_id, count($selected) >= 1 ? $selected[0] : ''); ?>><?php echo esc_html($term->name); ?></option> | |
| <?php endforeach; ?> | |
| </select> | |
| <?php | |
| } | |
| ?> | |
| <?php endif; ?> | |
| </div> | |
| <?php | |
| } | |
| // Usage example | |
| register_taxonomy("mytaxonomy", "page", array( | |
| "label" => "My Taxonomy", | |
| "meta_box_cb" => "my_admin_taxonomy_select_meta_box", | |
| )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment