如何在Wordpress自定义元框中保存复选框状态?

时间:2019-03-09 17:29:11

标签: php wordpress wordpress-theming

我已经编写了以下代码,但不会保存状态。该复选框始终恢复为选中状态:

<?php

/*META BOXES*/ 
function add_film_meta_boxes() {
add_meta_box('film_meta_data', 'Film info:', 'film_meta_box_callback', 'film', 'advanced', 'high');
}

function film_meta_box_callback( $post ) {
wp_nonce_field('save_film_meta_data', 'spanish_meta_box_nonce');
$spanish = get_post_meta( $post->ID, '_spanish_value_key', true);

echo '<label>Subtitles: </label>'; 
$spanish_subtitle_field = get_post_meta($post->ID, 'spanish_subtitle_field', true);
if($spanish_subtitle_field == "yes") {$spanish_subtitle_checked = 'checked="checked"';} else {$spanish_subtitle_checked = '';}

echo '<label><input type="checkbox" id="spanish_subtitle_field" name="spanish_subtitle_field" value="yes" '.$spanish_subtitle_checked.' /></label><label for="spanish_subtitle_field" style="font-weight:normal !important;">spanish &nbsp;</label>';
}

function save_film_meta_data ($post_id) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
    return;
if ( ! current_user_can( 'edit_post', $post_id )) 
    return;
if( ! isset($_POST['spanish_meta_box_nonce']) ) 
    return;
if ( ! wp_verify_nonce($_POST['spanish_meta_box_nonce'], 'save_film_meta_data') ) 
    return;
if ( ! isset( $_POST['spanish_subtitle_field'])) 
    return;
$spanish = isset($_POST['spanish_subtitle_field']) ? 'on' : 'off';
update_post_meta($post_id, '_spanish_value_key', $spanish);
} 
?>

该代码包含在我的functions.php文件中。

1 个答案:

答案 0 :(得分:0)

此行是错误的,这会使您的元框的值为“ on”或“ off”。

$spanish = isset($_POST['spanish_subtitle_field']) ? 'on' : 'off';

当您检查是否已选中时,您正在寻找“是”值。

if($spanish_subtitle_field == "yes") {$spanish_subtitle_checked = 'checked="checked"';} else {$spanish_subtitle_checked = '';}

因此,请尝试此新功能并检查是否有效:

function save_film_meta_data($post_id){
  if(! isset($_POST['spanish_meta_box_nonce'])){
    return;
  }
  if(!wp_verify_nonce($_POST['spanish_meta_box_nonce'],'save_film_meta_data')){
    return;
  }
  if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
    return;
  }
  if(! current_user_can('edit_post',$post_id)){
    return;
  }
  if( ! isset($_POST['spanish_subtitle_field'])){
    return;
  }
  $my_data = isset($_POST['spanish_subtitle_field']) ? $_POST['spanish_subtitle_field'] : 'no';
  update_post_meta($post_id,'_spanish_value_key',$my_data);

}