2011-09-23 18 views
10

WordPressのカスタムメタボックスにチェックボックスを追加しようとしていて、保存時に問題が発生しました。チェックボックスをオンにして投稿/ページを更新すると、再びチェックが外されます。それが必要としてWordPressのチェックボックスメタボックスを保存するには?

add_meta_box(
    'sl-meta-box-sidebar',  // id 
    'Sidebar On/Off',   // title 
    'sl_meta_box_sidebar',  // callback function 
    'page',      // type of write screen 
    'side',      // context 
    'low'      // priority 
); 

function sl_meta_box_sidebar() { 
    global $meta; sl_post_meta($post->ID); ?> 
    <input type="checkbox" name="sl_meta[sidebar]" value="<?php echo htmlspecialchars ($meta['sidebar']); ?>" />Check to turn the sidebar <strong>off</strong> on this page. 
} 

これは、「ページの編集」画面のサイドバーにあるチェックボックスを作成し、そこに問題はない:

はここで私が使用しているコードです。私はチェックボックスの値に何を入力すればいいのか分かりません。メタデータとして保存されたテキストフィールドを明示的に返します。私は最初に "checked"を使用してみました。このメタデータを使用するときの値)、チェックボックスも保存されませんでした。

function sl_save_meta_box($post_id, $post) { 
    global $post, $type; 

    $post = get_post($post_id); 

    if(!isset($_POST[ "sl_meta" ])) 
     return; 

    if($post->post_type == 'revision') 
     return; 

    if(!current_user_can('edit_post', $post_id)) 
     return; 

    $meta = apply_filters('sl_post_meta', $_POST[ "sl_meta" ]); 

    foreach($meta as $key => $meta_box) { 
     $key = 'meta_' . $key; 
     $curdata = $meta_box; 
     $olddata = get_post_meta($post_id, $key, true); 

     if($olddata == "" && $curdata != "") 
      add_post_meta($post_id, $key, $curdata); 
     elseif($curdata != $olddata) 
      update_post_meta($post_id, $key, $curdata, $olddata); 
     elseif($curdata == "") 
      delete_post_meta($post_id, $key); 
    } 

    do_action('sl_saved_meta', $post); 
} 

add_action('save_post', 'sl_save_meta_box', 1, 2); 

それは、テキストフィールドのために完璧に動作しますが、チェックボックスは、単に保存されません。

は、ここに私はこの問題は原因を想定しているすべてのメタデータを、セーブ機能です。保存機能が間違っているかどうかわからない、またはチェックボックスの値について何か不足している。

答えて

14

私はこれまでに問題があったし、ここで私はそれを解決した方法です。

まず、チェックボックスを作成します。

<?php 
function sl_meta_box_sidebar(){ 
    global $post; 
    $custom = get_post_custom($post->ID); 
    $sl_meta_box_sidebar = $custom["sl-meta-box-sidebar"][0]; 
?> 

<input type="checkbox" name="sl-meta-box-sidebar" <?php if($sl_meta_box_sidebar == true) { ?>checked="checked"<?php } ?> /> Check the Box. 
<?php } ?> 

次に、保存します。

<?php 
add_action('save_post', 'save_details'); 

function save_details($post_ID = 0) { 
    $post_ID = (int) $post_ID; 
    $post_type = get_post_type($post_ID); 
    $post_status = get_post_status($post_ID); 

    if ($post_type) { 
    update_post_meta($post_ID, "sl-meta-box-sidebar", $_POST["sl-meta-box-sidebar"]); 
    } 
    return $post_ID; 
} ?> 
関連する問題