LoginSignup
7
11

More than 5 years have passed since last update.

【WordPress】カスタム投稿タイプを自作する

Posted at

【WordPress】カスタム投稿タイプを自作する

カスタム投稿タイプを作成する場合、Custom Post Type UIなどのプラグインを利用すると工数なども削減出来て便利なのですが、カスタム投稿タイプがどう作られるのか中身をしっかり理解しておくため、今回はカスタム投稿タイプを自作してみる。

・function.phpにフックを追加し、カスタム投稿タイプを作成する。

function.php
<?php

〜〜省略〜〜

//======================================================================
// カスタム投稿タイプを自作
//======================================================================
function self_made_post_type() {
    register_post_type( 'self_made',
        array(
            'label' => '自作', //表示名
            'public'        => true, //公開状態
            'exclude_from_search' => false, //検索対象に含めるか
            'show_ui' => true, //管理画面に表示するか
            'show_in_menu' => true, //管理画面のメニューに表示するか
            'menu_position' => 5, //管理メニューの表示位置を指定
            'hierarchical' => true, //階層構造を持たせるか
            'has_archive'   => true, //この投稿タイプのアーカイブを作成するか
            'supports' => array(
                'title',
                'editor',
                'comments',
                'excerpt',
                'thumbnail',
                'custom-fields',
                'post-formats',
                'page-attributes',
                'trackbacks',
                'revisions',
                'author'
            ), //編集画面で使用するフィールド
        )
    );
}
add_action( 'init', 'self_made_post_type', 1 );

自作した関数(self_made_post_type)の中でregister_post_typeの引数に必要な項目を設定するだけで、自作投稿タイプが作成出来ます。これだけです。

・カスタム投稿タイプ作成前
before.png
デフォルトのWordPress管理メニューです。

・カスタム投稿タイプ作成後
after.png
管理メニューに「自作」というメニューが追加されています!

・自作投稿画面
after_post (1).png

「抜粋」や「カスタムフィールド」など、register_post_typeの第二引数のキー、「supports」に設定したフィールドが表示されています。

カスタム投稿タイプの自作自体は覚えてしまうと簡単で、プラグインを使用して作成するのと手間は変わらないかと思います。

7
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
11