Php 使用钩子和过滤器在DB中创建和更新检查值

Php 使用钩子和过滤器在DB中创建和更新检查值,php,wordpress,checkbox,filter,hook,Php,Wordpress,Checkbox,Filter,Hook,我有两个功能,一个是hook,另一个是filter。 钩子函数使用简单的输入类型(复选框)显示所有类别。 但我有一个过滤器功能的问题,当它被选中时,它被更新并存储在数据库中,但当我取消选中它时,我不能更新该字段以取消选中(在数据库中更新) 以下是钩子函数的代码: 由于复选框值仅在选中时提交(即无法指定未选中的值),因此必须使用用于创建复选框的数据。然后,您可以通过将它们与提交的数据(已选中)进行比较来判断哪些未选中 因为您使用[](数组)命名复选框,所以这是最好的方法 但是,如果您使用了诸如na

我有两个功能,一个是hook,另一个是filter。 钩子函数使用简单的输入类型(复选框)显示所有类别。 但我有一个过滤器功能的问题,当它被选中时,它被更新并存储在数据库中,但当我取消选中它时,我不能更新该字段以取消选中(在数据库中更新)

以下是钩子函数的代码:
由于复选框值仅在选中时提交(即无法指定未选中的值),因此必须使用用于创建复选框的数据。然后,您可以通过将它们与提交的数据(已选中)进行比较来判断哪些未选中

因为您使用[](数组)命名复选框,所以这是最好的方法

但是,如果您使用了诸如name=“bob”或name=“bob[1]”之类的固定名称,那么使所有值都可提交的最简单方法是使用相同的名称和未选中的值预先添加隐藏输入。勾选复选框将覆盖隐藏值



未选中的复选框不会提交。或者假设所有都未选中,然后处理选中的值。或者在每个具有相同名称和值=“0”的复选框之前放置一个隐藏输入。通过这种方式,勾选的复选框将覆盖0。使用与创建复选框相同的循环,使您拥有所有复选框,然后检查它们是否被勾选(假设未提交)。
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>';
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');
    }
}
}
<input type="hidden" name="bob" value="0" />
<input type="checkbox" name="bob" value="1" />