Wrordpressカスタム投稿
カスタム投稿(Custom Post Type)とは、通常の「投稿(post)」や「固定ページ(page)」以外に、独自の投稿タイプ(記事の種類)を作成できる機能です。
functions.phpでカスタム投稿とカスタムタクソノミーを作成する
functions.php
カスタム投稿タイプ:レッスンカレンダー(lesson-calendar)、よくある質問(qa)、スタッフ紹介(staff)
カスタムタクソノミー:レッスンカレンダーのカテゴリー(lesson-calendar-type)、よくある質問のカテゴリー(qa-type)、よくある質問のタグ(qa-tag)
function new_post_type() {
// レッスンカレンダー
register_post_type(
'lesson-calendar',
array(
'label' => 'レッスンカレンダー',
'labels' => array(
'name' => 'レッスンカレンダー',
'singular_name' => 'レッスンカレンダー',
'add_new_item' => '投稿を追加',
'edit_item' => '投稿を編集',
'view_item' => '投稿を表示',
'search_items' => '投稿を検索',
),
'public' => true,
'hierarchical' => false,
'has_archive' => true,
'show_in_rest' => true,
'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
'menu_position' => 5,
)
);
// よくある質問
register_post_type(
'qa',
array(
'label' => 'よくある質問',
'labels' => array(
'name' => 'よくある質問',
'singular_name' => 'よくある質問',
'add_new_item' => '投稿を追加',
'edit_item' => '投稿を編集',
'view_item' => '投稿を表示',
'search_items' => '投稿を検索',
),
'public' => true,
'hierarchical' => false,
'has_archive' => true,
'show_in_rest' => true,
'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
'menu_position' => 6,
)
);
// スタッフ紹介
register_post_type(
'staff',
array(
'label' => 'スタッフ紹介',
'labels' => array(
'name' => 'スタッフ紹介',
'singular_name' => 'スタッフ紹介',
'add_new_item' => '投稿を追加',
'edit_item' => '投稿を編集',
'view_item' => '投稿を表示',
'search_items' => '投稿を検索',
),
'public' => true,
'hierarchical' => false,
'has_archive' => true,
'show_in_rest' => true,
'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'),
'menu_position' => 7,
)
);
// カテゴリー(タクソノミー)設定
// レッスンカレンダー用カテゴリー(階層あり)
register_taxonomy(
'lesson-calendar-type',
'lesson-calendar',
array(
'label' => 'カテゴリー',
'labels' => array(
'name' => 'カテゴリー',
'popular_items' => 'よく使うカテゴリー',
'edit_item' => 'カテゴリーを編集',
'add_new_item' => '新規カテゴリーを追加',
'search_items' => 'カテゴリーを検索',
),
'public' => true,
'hierarchical' => true,
'show_in_rest' => true,
'rewrite' => array('slug' => 'lesson-calendar-type'),
)
);
// よくある質問用カテゴリー(階層あり)
register_taxonomy(
'qa-type',
'qa',
array(
'label' => 'カテゴリー',
'labels' => array(
'name' => 'カテゴリー',
'popular_items' => 'よく使うカテゴリー',
'edit_item' => 'カテゴリーを編集',
'add_new_item' => '新規カテゴリーを追加',
'search_items' => 'カテゴリーを検索',
),
'public' => true,
'hierarchical' => true,
'show_in_rest' => true,
'rewrite' => array('slug' => 'qa-type'),
)
);
// よくある質問用タグ(階層なし)
register_taxonomy(
'qa-tag',
'qa',
array(
'label' => 'よくある質問タグ',
'labels' => array(
'name' => 'タグ',
'popular_items' => 'よく使うタグ',
'edit_item' => 'タグを編集',
'add_new_item' => '新規タグを追加',
'search_items' => 'タグを検索',
),
'public' => true,
'hierarchical' => false, // タグは階層なし
'show_in_rest' => true,
'rewrite' => array('slug' => 'qa-tag'),
)
);
}
add_action('init', 'new_post_type');
