###発生している問題
投稿編集画面でカスタムフィールドが重複します。
画像のように、サイドに作った「言語」のフィールド(赤い部分)と同じ内容が、wp_insert_post
によって再度作られてしまう(緑の部分)。という問題が解決できません。
###ソースコード
次のようにして投稿編集画面にカスタムフィールドを表示しています。これは上の画像の赤い部分です。
■functions.php
php
1/* 2投稿編集画面にカスタムフィールド 3====================================*/ 4/* 表示 */ 5add_action( 'admin_menu', 'add_meta_field' ); 6function add_meta_field() { 7 add_meta_box( 'post_meta_language', '言語', 'create_post_meta_language', 'mypost', 'side' ); 8} 9function create_language() { 10 $keyname = 'post_meta_language'; 11 global $post; 12 // 保存されているカスタムフィールドの値を取得 13 $get_value = get_post_meta( $post->ID, $keyname, true ); 14 // radioの値 15 $data = ['ja', 'en']; 16 // nonceの追加 17 wp_nonce_field( 'action-' . $keyname, 'nonce-' . $keyname ); 18 // HTMLの出力 19 foreach( $data as $d ) { 20 $checked = ''; 21 if( $d === $get_value ) $checked = ' checked'; 22 echo '<label><input type="radio" name="' . $keyname . '" value="' . $d . '"' . $checked . '>' . $d . '</label>'; 23 } 24} 25 26/* 保存 */ 27add_action( 'save_post', 'save_meta_field' ); 28function save_meta_field( $post_id ) { 29 $custom_fields = ['post_meta_language']; 30 foreach( $custom_fields as $d ) { 31 if ( isset( $_POST['nonce-' . $d] ) && $_POST['nonce-' . $d] ) { 32 if( check_admin_referer( 'action-' . $d, 'nonce-' . $d ) ) { 33 34 if( isset( $_POST[$d] ) && $_POST[$d] ) { 35 update_post_meta( $post_id, $d, $_POST[$d] ); 36 } else { 37 delete_post_meta( $post_id, $d, get_post_meta( $post_id, $d, true ) ); 38 } 39 } 40 } 41 42 } 43}
ここまではいいとして、問題は次のwp_insert_post
のときのupdate_post_meta
です。このときに上の画像の緑の部分が勝手に生成されてしまい、同じカスタムフィールドが重複するという問題が発生してしまいます。
■single-form.php
php
1$value = array( 2 'post_type' => 'mypost', 3 'post_author' => get_current_user_id(), 4 'post_title' => $new_title, 5 'post_content' => $new_content, 6 'post_status' => $new_status, 7 'tax_input' => array( 'my_tag' => $new_tag_arr ), 8); 9$id = wp_insert_post($value); 10if( ($id) && !is_wp_error($id) ) { 11 update_post_meta($id, 'post_meta_language', $new_meta_language); 12}
このカスタムフィールドの重複を回避したいのですが、何かい方法はございませんでしょうか…。
もし良いアイディアがあればご指導よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー