0

I'm trying to save checkboxes values to categories for custom content type. I have printed the values of the IDs, the array with checkboxes values and all looks good, but at the end, the values doesn't save.

My custom content type is "portfolio", and his category "portfolio_categories".

Here is my code:

add_action( 'admin_menu', 'enhanced_portfolio_categories_remove_meta_box');
function enhanced_portfolio_categories_remove_meta_box(){
   remove_meta_box('portfolio_categoriesdiv', 'portfolio', 'normal');
}

//Add new taxonomy meta box
 add_action( 'add_meta_boxes', 'enhanced_portfolio_categories_add_meta_box');
 function enhanced_portfolio_categories_add_meta_box() {
     add_meta_box( 'portfolio_categoriesdiv', 'My Custom Portfolio Categories','enhanced_portfolio_categories_category_metabox','portfolio' ,'side','high');
 }

  function enhanced_portfolio_categories_category_metabox( $post ) {

      //Set up the taxonomy object and get terms
$taxonomy = 'portfolio_categories';
$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='my_categories[]' value='$term->term_id' />$term->name<br />";

            echo "</label></li>";

        }?>

        </ul>
        </div>
        <?php



    }

//    var_dump($categories);
  //          wp_set_post_terms( $_POST['post_ID'], $categories, 'category' );


$cat_ids = array_map( 'intval', (array)$_POST['my_categories']);
$cat_ids = array_unique( $cat_ids );

//foreach ($_POST['my_categories'] as $cat) {
  //  print_r('Category: ' .  $cat . '<br>');
//}
//print_r("POST ID:" . $_POST['post_ID']);


wp_set_object_terms( $_POST['post_ID'], $cat_ids, $taxonomy);
  • What does the following says: $result = wp_set_object_terms( $_POST['post_ID'], $cat_ids, $taxonomy); echo $result->get_error_message();? – Max Yudin Feb 15 '17 at 11:17
0

I have rethought the problem:

Finally, I resolve it with save_post hook:

function enhanced_portfolio_categories_save_post(){

    $terminos = array();
    foreach ($_POST['my_categories'] as $key) {
        $custom_tax = get_term_by('term_id', $key, 'portfolio_categories');
        array_push($terminos, $custom_tax->term_id);
    }

    wp_set_object_terms( $_POST['post_ID'], $terminos, 'portfolio_categories');

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.