从数组中取消设置项并更新wp选项

时间:2014-04-16 15:20:42

标签: php wordpress unset

我有一系列复选框,每个复选框都会在WordPress中触发ajax操作。它向我的php函数发送一个id号和复选框的状态。该函数检查两个wp_options。如果选中该复选框,它会在一个选项的数组中查找id号,如果它不在数组中,则会添加它。它还在第二个选项的数组中查找id号,如果它在数组中,则应该取消它。如果取消选中该复选框,则表示相反。

它成功地将项目添加到第一个选项的数组中,但我无法让它从第二个选项的数组中取消设置项目。它每次都返回“错误”。这是函数,减去nonce信息:

function my_required_fields(){
$field = $_POST['field'];       
$checked = $_POST['checked'];
$required_fields = get_option('ghsc_required_fields') ? unserialize(get_option('ghsc_required_fields')) : array();
$optional_fields = get_option('ghsc_optional_fields') ? unserialize(get_option('ghsc_optional_fields')) : array();  
if($checked === 'yes'):
    if(!in_array($field, $required_fields)): $required_fields[] = $field; endif;
    if(in_array($field, $optional_fields)): unset($optional_fields[$field]); endif;     
elseif($checked === 'no'):
    if(!in_array($field, $optional_fields)): $optional_fields[] = $field; endif;
    if(in_array($field, $required_fields)): unset($required_fields[$field]); $required_fields = array_values($required_fields); endif;      
endif;
$update_required = update_option('ghsc_required_fields', serialize($required_fields));
$update_optional = update_option('ghsc_optional_fields', serialize($optional_fields));  
$response = ($update_required && $update_optional) ? 'success' : 'error';
$response = json_encode($response); header( "Content-Type: application/json" ); echo $response; exit;
}

知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

我解决了这个问题。需要使用array_keys(或替代方法)来取消设置键而不是值,并且还需要检查选项的值是否已更改,因为如果它没有,则返回false。见下文:

function my_required_fields(){
$field = $_POST['field'];       
$checked = $_POST['checked'];
$required_fields = get_option('ghsc_required_fields') ? unserialize(get_option('ghsc_required_fields')) : array();
$optional_fields = get_option('ghsc_optional_fields') ? unserialize(get_option('ghsc_optional_fields')) : array();  
if($checked === 'yes'):
    if(!in_array($field, $required_fields)): $required_fields[] = $field; endif;
    if(in_array($field, $optional_fields)): foreach(array_keys($optional_fields, $field, true) as $key) unset($optional_fields[$key]); endif;       
elseif($checked === 'no'):
    if(!in_array($field, $optional_fields)): $optional_fields[] = $field; endif;
    if(in_array($field, $required_fields)): foreach(array_keys($required_fields, $field, true) as $key) unset($required_fields[$key]); endif;       
endif;
$update_required = (get_option('ghsc_required_fields') === serialize($required_fields) ? 1 : update_option('ghsc_required_fields', serialize($required_fields)));
$update_optional = (get_option('ghsc_optional_fields') === serialize($optional_fields) ? 1 : update_option('ghsc_optional_fields', serialize($optional_fields)));   
$response = ($update_required && $update_optional) ? 'success' : 'error';
$response = json_encode($response); header( "Content-Type: application/json" ); echo $response; exit;
}