プラグインを使わずにカスタムフィールドを設定する

プラグインを使わずにカスタムフィールドを設定する

Advanced Custom Fieldsとの併用も可能。
入力項目に変数を用いる場合などのカスタムに使用。

ソースの例では天気の入力Fieldを作成。
customfield

<?php
add_action('admin_menu', 'add_weather');
add_action('save_post', 'save_weather');

function add_weather(){
 if(function_exists('add_weather')){
  add_meta_box('weather1', '天気', 'insert_weather', 'post', 'normal', 'high');
 }
}

function insert_weather(){
 global $post;
 wp_nonce_field(wp_create_nonce(__FILE__), 'my_nonce');
 echo '<label class="hidden" for="weather">天気</label><input type="text" name="weather" size="60" value="'.esc_html(get_post_meta($post->ID, 'weather', true)).'" />';
 echo '<p>作成した日の天気を入力します。</p>';
}

function save_weather($post_id){
 $my_nonce = isset($_POST['my_nonce']) ? $_POST['my_nonce'] : null;
 if(!wp_verify_nonce($my_nonce, wp_create_nonce(__FILE__))) {
  return $post_id;
 }
 if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; }
 if(!current_user_can('edit_post', $post_id)) { return $post_id; }

 $data = $_POST['weather'];

 if(get_post_meta($post_id, 'weather') == ""){
  add_post_meta($post_id, 'weather', $data, true);
 }elseif($data != get_post_meta($post_id, 'weather', true)){
  update_post_meta($post_id, 'weather', $data);
 }elseif($data == ""){
  delete_post_meta($post_id, 'weather', get_post_meta($post_id, 'weather', true));
 }
}
?>

表示にはget_post_metaを用いる

<?php echo get_post_meta( $post->ID , 'weather' , true ); ?>

参考サイト

WebScripter.jp
[ WordPress ] 独自のカスタムフィールドを設定する
http://webscripter.jp/technical-note/set-the-original-custom-field-wordpress/