I'm building my own metabox with checkboxes. I want to save the values of the checkboxes I've cheked as categories (IDs).
I have build an array to append the values of the checkboxes, but it only saves the last checkbox I have checked.
I'm trying to save the values using the following functions.
wp_set_post_categories(); wp_set_object_terms();
In addition, when I click the submit button for create / edit post, whatever the function I use, it always saves the last value of checkbox.
Here is my code:
add_action( 'admin_menu', 'my_enhanced_categories_remove_meta_box');
function my_enhanced_categories_remove_meta_box(){
remove_meta_box('categorydiv', 'post', 'normal');
}
//Add new taxonomy meta box
add_action( 'add_meta_boxes', 'my_enhanced_categories_add_meta_box');
function my_enhanced_categories_add_meta_box() {
add_meta_box( 'category-all', 'Custom Portfolio Categories','my_enhanced_categories_category_metabox','post' ,'side','high');
}
$postterms = get_the_terms( $post->ID,$taxonomy );
function my_enhanced_categories_category_metabox( $post ) {
//Set up the taxonomy object and get terms
$taxonomy = 'category';
$tax = get_taxonomy($taxonomy);//This is the taxonomy object
//The name of the form
$name = 'tax_input[' . $taxonomy . ']';
//Get all the terms for this taxonomy
$terms = get_terms($taxonomy,array('hide_empty' => 0));
echo '<div id="' . $taxonomy . '-all" class="tabs-panel">';
echo '<ul id="' . $taxonomy . '-checklist" class="list-' . $taxonomy . 'categorychecklist form-no-clear">';
$categories = array();
foreach($terms as $term){
$id = $taxonomy.'-'.$term->term_id;
echo "<li id='$id'><label>";
echo "<input type='checkbox' id='in-$id' name='{$name}-$term->term_id' value='$term->term_id' />$term->name<br />";
echo "</label></li>";
$key_tax = ($_POST['tax_input']);
if (!empty($key_tax)) {
array_push($categories, array_values($key_tax));
/*wp_set_post_categories( $_POST['post_ID'], array_values($key_tax)[0]); */
}
}?>
</ul>
</div>
<?php
}
// var_dump($categories);
// wp_set_post_terms( $_POST['post_ID'], $categories, 'category' );
wp_set_object_terms( $_POST['post_ID'], $categories, 'category');
var_dump($categories);