プラグインを使わずに、独自のカスタムフィールドを追加する方法をご紹介いたします。
独自のカスタムフィールドをプラグインなしで実装したい場合は、ぜひ参考にしてください。
スポンサードリンク
プラグインを使わずに独自のカスタムフィールドを追加する方法
独自のカスタムフィールドを追加するには、add_meta_box()関数を使います。
1 | add_meta_box( '$id', $title, $callback, $page, $context, $priority ); |
| $id | 編集画面に追加されるメタボックスを包括するID |
| $title | メタボックスに表示されるタイトル |
| $callback | 入力エリアの関数名 |
| $page | 投稿タイプ名 |
| $context | メタボックスを配置する場所 |
| $priority | 優先度 |
実際にカスタムフィールドを追加するためのコードは以下の通りです。これを適用しているテーマのfunctions.phpに追加します。
functions.php
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //カスタムフィールドのメタボックス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()では、入力された値を保存します。
上記を追加すると、投稿の編集画面に以下のような項目が追加されます。
入力されたカスタムフィールドの値を取得・出力する
カスタムフィールドの値を取得して出力するには、テーマ内に以下を記述します。
01 02 03 04 05 06 07 08 09 10 11 | <!-- テキストの出力 --><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><!-- チェックボックス --><?phpif( get_post_meta($post->ID,'custom_checkbox',true) == "is-on" ) {echo "チェックあり";} else {echo "チェックなし";}?> |
カスタムフィールドの値はget_post_meta()関数を使って出力します。
チェックボックスの方は、チェックが入っている場合は「is-on」という値が入るように設定してあるので、それを使って条件分岐させます。
あとがき
カスタムフィールドは、Advanced Custom FieldsやCustom Field Template等のプラグインを使えば簡単に追加することができますが、シンプルなものであれば独自に追加しても難しくはないですね。
参考になれば幸いです。