カテゴリー
WordPress

カスタム投稿タイプ

WordPress のカスタム投稿タイプ。頻繁に設定するものでもなく、機会があるたび、自分で書いた古いコードやネットで再検索するのでメモ。

基本形

例えば、「ニュース」ようのカスタム投稿タイプを作るとする。「my_post_type」としている関数名は、既存の関数名と被らなければ好きな名前で。

add_action('init', 'my_post_type');

function my_post_type()
{
    register_post_type(
        'news',
        array(
            'label' => 'ニュース',
            'labels' => array(
                'all_items' => 'ニュース一覧',
            ),
            'public' => true,
            'menu_position' => 5,
            'has_archive' => true,
        )
    );
}

余計なコードは書きたくないので、デフォルト値や自動的に継承される値をわざわざ書かなければ、私的にはこれが基本かな。

基本形+階層化カテゴリ

先の「my_post_type」関数内に、階層化カテゴリの設定も追加。「’hierarchical’ => true」がないとタグになる。

add_action('init', 'my_post_type');

function my_post_type()
{
    register_post_type(
        'news',
        array(
            'label' => 'ニュース',
            'labels' => array(
                'all_items' => 'ニュース一覧',
            ),
            'public' => true,
            'menu_position' => 5,
            'has_archive' => true,
        )
    );

    register_taxonomy(
        'news_cat',
        'news',
        array(
            'hierarchical' => true,
        )
    );
}

複数追加

たとえば、「ニュース」と「メニュー」の二つを追加するなら、関数内に二つ「register_post_type」を設定すれば OK。

add_action('init', 'my_post_type');

function my_post_type()
{
    register_post_type(
        'news',
        array(
            'label' => 'ニュース',
            'labels' => array(
                'all_items' => 'ニュース一覧',
            ),
            'public' => true,
            'menu_position' => 5,
            'has_archive' => true,
        )
    );

    register_post_type(
        'menu',
        array(
            'label' => 'メニュー',
            'labels' => array(
                'all_items' => 'メニュー一覧',
            ),
            'public' => true,
            'menu_position' => 5,
            'has_archive' => true,
        )
    );
}

リンク

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です