サポート » 使い方全般 » 管理画面にカスタムボックスを追加しようとするとundefinedエラー

  • 解決済 takuya1108

    (@takuya1108)


    以下のソース入力でカスタムボックスを追加しようとしましたが、
    (本来はもう10~20くらいのメタキーがありますが、長くなりすぎるので省略しました)

    Notice: Undefined index: example in functions.php on line xx

    のようなエラーがメタボックス内に出ます。投稿画面のカスタムボックスのhtmlはきちんと表示されますが、エラーも同時に表示されます。
    (セレクトボックス、チェックボックスはUndefined variableエラーです)
    更新をクリックすると、また同じPHPエラーが出ます。

    inputテキストフォームのエラーはおそらくメタキーがないということだということはわかりましたが、解決策が見つからないので(セレクトボックス、チェックボックスに至っては原因すらもわかりません…)どうすればよいのかわからず困っています。どなたかご教授いただけると非常に助かります。

    <?php
    add_action( 'admin_init', 'meta_create' );
    function meta_create() {
    	add_meta_box('example_meta', '概要', 'example_meta_html','post');
    }
    
    function example_meta_html () {
    	global $post;
    	$custom = get_post_custom($post->ID);
    
    if(!empty($custom)) {
    	$example = $custom["example"][0];
            $example_select = $custom["example_select"][0];
            $example_check = $custom["example_check"][0];
    }
    	echo '<input type="hidden" name="events-nonce" id="events-nonce" value="' . wp_create_nonce( 'events-nonce' ) . '" />';
    ?>
    <input name="example" value="<?php if(isset($example)) echo $example; ?>" size="65">
    <select name="example_select" id="example_select"><option value="test1" <?php selected( $example_select, 'test1' ); ?>>test1</option><option value="test2" <?php selected( $example_select, 'test2' ); ?>>test2</option></select>
    <input type="checkbox" name="example_check" id="example_check" <?php checked( $example_check, 'on' ); ?>><label>チェックボックス</label>
    <?php
    }
    add_action ('save_post', 'save_example');
    function save_example($post_id){
    	global $post;
    	if ( !wp_verify_nonce( $_POST['events-nonce'], 'events-nonce' )) {
    		return $post_id;
    	}
    	if ( !current_user_can( 'edit_post', $post->ID )) {
    		return $post_id;
    	}
            update_post_meta($post->ID, 'example', $_POST['example']);
        update_post_meta($post->ID, 'example_select', $_POST['example_select']);
        update_post_meta($post->ID, 'example_check', $_POST['example_check']);
    }
    ?>
2件の返信を表示中 - 1 - 2件目 (全2件中)
  • モデレーター jim912

    (@jim912)

    takuya1108さん、こんにちは。

    この Undefined エラーは、存在配列の要素を参照しようとしたときに発生します。
    上記の例で言えば、$custom の配列に

    $custom["example"][0]

    が存在していないにも関わらず、これを変数に代入しようとしているため、エラーとなるのです。

    このような場合は、PHPの isset 関数をつかって分岐処理をおこなってください。

    $example = isset( $custom["example"][0] ) ? $custom["example"][0] : '';

    トピック投稿者 takuya1108

    (@takuya1108)

    jim912さん>
    非常に助かりました。ありがとうございました!
    教えていただいた処理でエラーが出なくなりました。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「管理画面にカスタムボックスを追加しようとするとundefinedエラー」には新たに返信することはできません。