プラグインを使わず投稿タイプを追加
- functions.phpに以下の関数を追加
- 具体的なオプションについてはcodex参照 register_post_type()
- taxonomyは投稿と同じものを使えるが、分けたほうがいいかも
// functions.php
function create_posttype() {
register_post_type( 'products',
// オプション設定
array(
'labels' => array(
'name' => __( '製品一覧' ),
'singular_name' => __( '製品情報' )
),
'public' => true,
'has_archive' => true, // 一覧ページを有効化する場合true
'taxonomies' => array('category','post_tag'),
'rewrite' => array('slug' => 'products'),
'show_in_rest' => true,
)
);
}
add_action( 'init', 'create_posttype' );
カスタム投稿タイプの表示方法
- 投稿タイプごとに使用するテンプレートを分ける場合は次のようにする
- ループ処理は通常の記事と同じでOK
// 一覧ページ
archive-{post_type}.php
archive-products.php
// 個別記事
single-{post-type}.php
single-products.php
カスタム投稿タイプを表示しようとすると404エラーになる場合の対策
- 新しくカスタム投稿タイプを追加するときは
flush_rewrite_rules();
を追記する - この関数を使ってリライトルールを更新する必要がある
- 何度かブラウザを更新して記事が表示されたら
flush_rewrite_rules();
を削除する
// 追加した関数の続きに追記
function create_posttype() {
// 省略
}
add_action( 'init', 'create_posttype' );
// 記事が表示されたら削除するのを忘れずに
flush_rewrite_rules();