プラグインを使わずに、独自のカスタムフィールドを追加する方法をご紹介いたします。
独自のカスタムフィールドをプラグインなしで実装したい場合は、ぜひ参考にしてください。
プラグインを使わずに独自のカスタムフィールドを追加する方法
独自のカスタムフィールドを追加するには、add_meta_box()関数を使います。
add_meta_box( '$id', $title, $callback, $page, $context, $priority );
$id | 編集画面に追加されるメタボックスを包括するID |
$title | メタボックスに表示されるタイトル |
$callback | 入力エリアの関数名 |
$page | 投稿タイプ名 |
$context | メタボックスを配置する場所 |
$priority | 優先度 |
実際にカスタムフィールドを追加するためのコードは以下の通りです。これを適用しているテーマのfunctions.phpに追加します。
//カスタムフィールドのメタボックス
function add_custom_fields() {
add_meta_box('meta_id', '独自のカスタムフィールド', 'insert_custom_fields', 'post', 'normal');
}
add_action('admin_menu', 'add_custom_fields');
//カスタムフィールドの入力エリア
function insert_custom_fields() {
global $post;
echo '<p>テキストの入力: <input type="text" name="custom_fields" value="' . get_post_meta($post->ID, 'custom_fields', true) . '" size="50"></p>';
if (get_post_meta($post->ID, 'custom_checkbox', true) == "is-on") { //チェックされていたらチェックボックスの$custom_checkbox_checkにcheckedを挿入
$custom_checkbox_check = "checked";
}
echo '<p>チェックボックス: <input type="checkbox" name="custom_checkbox" value="is-on" ' . $custom_checkbox_check . '></p>';
}
//カスタムフィールドの値を保存
function save_custom_fields($post_id) {
if (!empty($_POST['custom_fields'])) { //入力済みの場合
update_post_meta($post_id, 'custom_fields', $_POST['custom_fields']); //値を保存
} else { //未入力の場合
delete_post_meta($post_id, 'custom_fields'); //値を削除
}
if (!empty($_POST['custom_checkbox'])) { //チェックされている場合
update_post_meta($post_id, 'custom_checkbox', $_POST['custom_checkbox']);
} else { //チェックされていない場合
delete_post_meta($post_id, 'custom_checkbox');
}
}
add_action('save_post', 'save_custom_fields');
まず、add_meta_box()関数でメタボックスを追加します。IDやラベル等の値は変更してください。
insert_custom_fields()では、出力するフィールドを設定します。ここでは、テキストフィールドとチェックボックスを出力しています。
save_custom_fields()では、入力された値を保存します。
上記を追加すると、投稿の編集画面に以下のような項目が追加されます。

入力されたカスタムフィールドの値を取得・出力する
カスタムフィールドの値を取得して出力するには、テーマ内に以下を記述します。
<!-- テキストの出力 -->
<p>改行なし:<?php echo esc_html(get_post_meta($post->ID,'custom_fields',true)); ?></p>
<p>改行あり:<?php echo nl2br(get_post_meta($post->ID,'custom_fields',true)); ?></p>
<!-- チェックボックス -->
<?php
if( get_post_meta($post->ID,'custom_checkbox',true) == "is-on" ) {
echo "チェックあり";
} else {
echo "チェックなし";
}
?>
カスタムフィールドの値はget_post_meta()関数を使って出力します。
チェックボックスの方は、チェックが入っている場合は「is-on」という値が入るように設定してあるので、それを使って条件分岐させます。
あとがき
カスタムフィールドは、Advanced Custom FieldsやCustom Field Template等のプラグインを使えば簡単に追加することができますが、シンプルなものであれば独自に追加しても難しくはないですね。
なお、画像フィールドを追加したい場合は、こちらの記事が参考になるかと思います。
画像を保存する場合はどうすればいいですかぁ?