Navigation

カスタム投稿タイプごとに管理画面にカスタムフィールドを追加する方法

📅 7月 7, 2025
👤
1 min read

概要

  • ユースケース:WordPressの管理画面にカスタムフィールドを追加することで、カスタム投稿タイプごとに独自の情報を入力できるようにするため。
  • 前提条件:WordPressのテーマ内でカスタム投稿タイプを定義していること。

サンプルコード


// functions.php などの適切なファイルに以下のコードを追加
add_action('admin_init', 'custom_post_type_custom_fields');
function custom_post_type_custom_fields(){
    add_meta_box('custom_post_meta_box', 'カスタムフィールド', 'display_custom_post_meta_box', 'custom_post_type', 'normal', 'high');
}
function display_custom_post_meta_box($post){
    $custom_field_value = get_post_meta($post->ID, '_custom_field_key', true);
    echo '<label for="custom_field">カスタムフィールド:</label>';
    echo '<input type="text" id="custom_field" name="custom_field" value="' . esc_attr($custom_field_value) . '">';
}
add_action('save_post', 'save_custom_post_custom_fields');
function save_custom_post_custom_fields($post_id){
    if(array_key_exists('custom_field', $_POST)){
        update_post_meta($post_id, '_custom_field_key', sanitize_text_field($_POST['custom_field']));
    }
}

解説

  • `add_meta_box`関数を使用して、カスタムフィールドを管理画面に追加している。
  • `display_custom_post_meta_box`関数では、カスタムフィールドの入力フィールドを表示している。
  • `save_custom_post_custom_fields`関数では、カスタムフィールドの値を保存している。

ベストプラクティス

  • カスタムフィールドの表示や保存処理は、セキュリティを考慮して適切にサニタイズすること。
  • カスタムフィールドのデータを利用する際には、適切なエスケープ処理を行うことでセキュリティを確保する。
← Back to WordPress