0
0

More than 3 years have passed since last update.

Wordpressでプラグインを使わずカスタム投稿タイプを追加する方法

Posted at

プラグインを使わず投稿タイプを追加

  • 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();
0
0
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
0
0