I have a custom post type with its own taxonomy, basically ‘show venues’ is the post type and venue-regions is the taxonomy.
Seeing how a venue cant exsist in mutiple regions, I’ve removed the default metta box and added my own as a dropdown using wp_dropdown_categories()
. The taxonomy items are being output and appear as I’d like them, BUT they are not being submitted and the dropdown list dosen’t hold the selection after submit. I’ve tried as far as I am able to look at the various attributes of the origional metabox and tried to apply these to the drop down but so far I’ve not had any joy.
I’ve looked at some the various posts on WPSE and havent been able to sus out where I’m going wrong.
Can anyone elaborate as to what my next steps should be/what parts Im missing?
<?php
// remove the default taxononomy
add_action( 'admin_menu', 'tr_remove_meta_box');
function tr_remove_meta_box(){
remove_meta_box('venue-regiondiv', 'venue', 'normal');
}
//Add new taxonomy meta box
add_action( 'add_meta_boxes', 'tr_add_meta_box');
function tr_add_meta_box() {
add_meta_box( 'venue-region-dropdowndiv', 'What region is this venue in?','tr_venuesTaxonomydropdown_metabox','venue' ,'side','core');
}
//Callback to set up the metabox
function tr_venuesTaxonomydropdown_metabox( $post ) {
$taxonomy = 'venue-region';
//The name of the form
$name = 'tax_input[' . $taxonomy . '][]';
$id = $taxonomy.'dropdown';
//Get current and popular terms
$postterms = get_the_terms( $post->ID,$taxonomy );
$current = ($postterms ? array_pop($postterms) : false);
$current = ($current ? $current->term_id : 0);
?>
<div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv">
<!-- Display taxonomy terms -->
<div id="<?php echo $taxonomy; ?>-all" class="tabs-panel">
<?php $args = array(
'show_option_all' => 'Choose a region',
'show_option_none' => '',
'orderby' => 'ID',
'order' => 'ASC',
'show_count' => 0,
'hide_empty' => 0,
'child_of' => 0,
'exclude' => '',
'echo' => 1,
'selected' => 1,
'hierarchical' => 1,
'name' => $name,
'id' => $id,
'class' => 'form-no-clear',
'depth' => 0,
'tab_index' => 0,
'taxonomy' => $taxonomy,
'hide_if_empty' => true
); ?>
<?php wp_dropdown_categories($args); ?>
</div>
</div>
<?php
}
get post id
get selected region
build hierarchical dropdown
Using the
wp_dropdown_categories()
function there’s a parameter you can use calledselected
which you would assign the selected category ID. You should also standardize the name of your select so it’s easier to save:You need to save the postmeta and retrieve the postmeta ( via
get_post_meta()
). It looks like in your example you’re getting the first term which may not always be the selected term. Then you assign the$selected_id
to theselected
index in our arguments.