Skip to content

Instantly share code, notes, and snippets.

@eduardozulian
Last active May 5, 2024 14:45
Show Gist options
  • Save eduardozulian/4a857c671751f34cf7be to your computer and use it in GitHub Desktop.
Save eduardozulian/4a857c671751f34cf7be to your computer and use it in GitHub Desktop.
Callback function for 'meta_box_cb' argument inside register_taxonomy() that replaces the regular checkboxes with a plain dropdown list
<?php
/**
* Callback function for taxonomy meta boxes
*
* A simple callback function for 'meta_box_cb' argument
* inside register_taxonomy() that replaces the regular
* checkboxes with a plain dropdown list
*
* @param [type] $post [description]
* @param [type] $box [description]
* @link http://wordpress.stackexchange.com/a/148965
*/
function my_taxonomy_meta_box_callback( $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 );
?>
<div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv">
<?php
$name = ( $taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $taxonomy . ']';
echo "<input type='hidden' name='{$name}[]' value='0' />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks.
$term_obj = wp_get_object_terms( $post->ID, $taxonomy ); //_log($term_obj[0]->term_id)
if ( ! empty( $term_obj ) ) {
wp_dropdown_categories( array(
'taxonomy' => $taxonomy,
'hide_empty' => 0,
'name' => "{$name}[]",
'selected' => $term_obj[0]->term_id,
'orderby' => 'name',
'hierarchical' => 0,
'show_option_none' => '&mdash;',
'class' => 'widefat'
) );
}
?>
</div>
<?php
}
?>
@bustapaladin
Copy link

Do you know by any chance the default code? I want to edit a bit like add some echos here and there but not change it to a dropdown like the code above does.

@jerturowetz
Copy link

Copy link

ghost commented Sep 5, 2018

why does it add another category automatically?

Copy link

ghost commented Sep 6, 2018

when I publish the post it automatically creates another taxonomy in the list.

@iokusanya
Copy link

Hey eduardo..this is really great!!

I was wondering, is there a way to retain the add_new_item link that you normally get when you use register_taxonomy?

i.e.

'labels' => array(
'name' => 'Category Sorting',
'new_item_name' => 'New Category',
'add_new_item' => 'Add New Category',
),

Thanks so much for your help.

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