I have two functions one is hook and the other is filter.
Hook function displays all categories with input type(checkbox) thats simple.
But I have a problem with filter function when it is checked it’s updated and stored in DB but when I uncheck it I can’t update that field to be unchecked (to be updated in DB)
Here is the code of hook function:
function my_account_add_extra_field_kategorija() {
global $current_user;
$taxonomy = 'category';
$orderby = 'name';
$show_count = 1; // 1 for yes, 0 for no
$pad_counts = 1; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$fcats = '';
$i = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => 0
);
$cats = get_categories( $args );
print '<ul>';
foreach($cats as $cat){ if($cat->parent == 0){ $fcats .= $cat->cat_ID.",";
$cat_name = $cat->cat_name;
$userID = $current_user->ID;
$get_meta_value = get_the_author_meta( $cat_name, $userID );
if($i%2){ $ex ="space"; }else{ $ex =""; }
if($i == 10){ print '<div class="clearfix"></div>'; $ex =""; $i=0;}
print '<li>';
if($get_meta_value == 1 ) {
print '<input type="checkbox" name="sel_cat[]" value="'.$cat_name.'" checked="checked" ';
print '/>'.$cat_name;
} else {
print '<input type="checkbox" name="sel_cat[]" value="'.$cat_name.'" ';
print '/>'.$cat_name;
}
print '</li>';
$i++; } }
print '</ul>';
print '<div class="clearfix"></div>';
}
and here is the filters function:
function my_account_update_extra_field_kategorija() {
global $current_user;
$user_id = $current_user->ID;
if(isset($_POST['sel_cat'])){
foreach($_POST['sel_cat'] as $check) {
update_user_meta($user_id, $check, '1');
}
}
}
Since checkbox values are only submitted when checked (ie there is no way of specifying an unchecked value), then you will have to use the data that you used to create the checkboxes. You can then tell which were unchecked by comparing them with the data submitted (checked).
Since you are naming your checkboxes with [] (array) this is the best method.
If however you used fixed names like name=”bob” or name=”bob[1]” then the easiest way to make all values submittable is to prepend a hidden input with the same name and the unchecked value. Ticking the checkbox will then over-write the hidden value.
ie