Checkbox selection for Taxonomy terms
-
Hi everbody,
I created a new ‘gender’ taxonomy, for which I automatically registered the terms ‘men’ and ‘women’. For this new taxonomy I needed to create a custom metabox with checkboxes for every term of the gender taxonomy because of the user experience (the option to choose a gender (or multiple) for each post is very important for the site I’m working on, so it has to be quick and easy to do).
This is all working just fine (code below), but I can’t seem to find a way to save the settings from the checkboxes. I’ve tried many things, eventually I got it working with ‘tax_input[gender][]’ but with the massive drawback that when editing the post you can’t uncheck all checkboxes because that won’t save the new setting. Thats because unchecked checkboxes do not send any data to the $_POST event.
So I’ve tried to create a save function hooked into ‘save_post’ (code below), but so far that didn’t work out. Does anybody have a idea how to make this work?, thanks in advance.
— Wessel
The codes:
– Metabox callback:
Echo’s all terms registered for the ‘gender’ taxonomy (this works except saving the settings)function meta_gender_callback($post) { wp_nonce_field(basename(__FILE__), 'meta_gender_nonce'); // All terms: $gender_terms = get_terms('gender', 'hide_empty=0'); // All terms currently assigned to the post: $post_terms = wp_get_object_terms($post->ID, 'gender'); // All terms currently assigned to the post inside an array: $current_terms = array(); if ($post_terms) { foreach ($post_terms as $post_term) { $current_terms[] = $post_term->term_id; } } // Echo list: echo('<ul>'); foreach ($gender_terms as $term) { if (in_array($term->term_id, $current_terms)) { echo('<li id="gender-'.$term->term_id.'"> <label> <input value="'.$term->slug.'" type="checkbox" id="in-gender-'.$term->term_id.'" name="gender-data[]" checked="checked" />'.$term->name.' </label> </li>'); } else { echo('<li id="gender-'.$term->term_id.'"> <label> <input value="'.$term->slug.'" type="checkbox" id="in-gender-'.$term->term_id.'" name="gender-data[]" />'.$term->name.' </label> </li>'); } } echo('</ul>'); }
– Saving function (this does NOT work):
First does some default checks and then tries to save the new settings set by the checkboxesfunction save_meta_gender($post_id, $post, $update) { if (!isset( $_POST['meta_gender_nonce'] ) || !wp_verify_nonce( $_POST['meta_gender_nonce'], basename( __FILE__ ) ) ){ return; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } if (!current_user_can( 'edit_post', $post_id ) ){ return; } if (isset($_POST['gender-data'])) { $gender_data = $_POST['gender-data']; wp_set_object_terms($post_id, $gender_data, 'gender' ); } } add_action('save_post', 'save_meta_gender', 10, 3);
- The topic ‘Checkbox selection for Taxonomy terms’ is closed to new replies.