カスタム投稿タイプの設定方法(functions.php)

更新日:2025/03/06

WordPress で独自のコンテンツタイプを作成するカスタム投稿タイプの設定は、一般的に functions.php ファイルで行います。以下にその基本的な方法と詳細なオプションを説明します。

function create_custom_post_type() {
    register_post_type('product',
        array(
            'labels' => array(
                'name' => '商品',
                'singular_name' => '商品'
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array('title', 'editor', 'thumbnail'),
            'menu_icon' => 'dashicons-cart'
        )
    );
}
add_action('init', 'create_custom_post_type');

この例では、「商品」というカスタム投稿タイプを作成しています。

主要なパラメータの詳細説明

1. register_post_type の第一引数

カスタム投稿タイプの識別子(スラッグ)です。英数字の小文字とアンダースコアのみを使用します。例: 'product', 'team_member', 'portfolio'

2. labels 配列

管理画面での表示名を設定します。主な項目は:

'labels' => array(
    'name' => '商品', // 複数形の名前
    'singular_name' => '商品', // 単数形の名前
    'add_new' => '新規追加',
    'add_new_item' => '新しい商品を追加',
    'edit_item' => '商品を編集',
    'new_item' => '新しい商品',
    'view_item' => '商品を表示',
    'search_items' => '商品を検索',
    'not_found' => '商品が見つかりませんでした',
    'not_found_in_trash' => 'ゴミ箱に商品はありません'
)

2. 基本的な表示設定

'public' => true, // 一般公開するか
'publicly_queryable' => true, // 一般クエリで取得可能か
'show_ui' => true, // 管理UIに表示するか
'show_in_menu' => true, // 管理メニューに表示するか
'menu_position' => 5, // メニューの位置(5=投稿の下)
'menu_icon' => 'dashicons-cart', // アイコン(Dashiconsから選択)
'show_in_admin_bar' => true, // 管理バーに表示するか
'show_in_nav_menus' => true, // ナビゲーションメニューに表示するか
'can_export' => true, // エクスポート機能を有効にするか
'has_archive' => true, // アーカイブページを持つか
'exclude_from_search' => false, // 検索から除外するか
'show_in_rest' => true, // REST API(Gutenbergエディタ)で使用可能にするか

4. 投稿タイプの機能設定

'supports' => array(
    'title', // タイトル
    'editor', // 本文エディタ
    'author', // 投稿者
    'thumbnail', // アイキャッチ画像
    'excerpt', // 抜粋
    'comments', // コメント
    'revisions', // リビジョン
    'custom-fields', // カスタムフィールド
    'page-attributes', // 属性(親・テンプレート・順序)
    'post-formats' // 投稿フォーマット
)

5. パーマリンク設定

'rewrite' => array(
    'slug' => 'products', // URLのスラッグ
    'with_front' => true, // パーマリンク構造の先頭部分を含めるか
    'pages' => true, // ページ分割を有効にするか
    'feeds' => true, // フィードを有効にするか
)

6. その他設定

'hierarchical' => false, // 階層構造を持つか(true=固定ページ型、false=投稿型)
'capability_type' => 'post', // 権限タイプ('post'または'page')
'taxonomies' => array('category', 'post_tag'), // 既存タクソノミーを有効にする

ベストプラクティス

  1. テーマの functions.php への直接実装ではなく、プラグインとして実装するか、Custom Post Type UI などのプラグインを使用することをお勧めします(テーマ変更時にも設定が保持されます)。
  2. カスタム投稿タイプ名は、既存のものと衝突しないよう、ユニークな名前にします。
  3. init フックを使用して登録するのが標準的です。
  4. アーカイブテンプレート(archive-{post_type}.php)や単一投稿テンプレート(single-{post_type}.php)をテーマに追加することで、表示をカスタマイズできます。

以上が、functions.php でのカスタム投稿タイプ設定の基本的な方法です。用途に合わせて必要なオプションを選択して実装してください。

人気記事ランキング
話題のキーワードから探す